diff --git a/README b/README old mode 100644 new mode 100755 index bda4853..a1ccd10 --- a/README +++ b/README @@ -10,6 +10,12 @@ the printer can natively print PDF. That is to say, CUPS needs to already be configured with a PDF filter. Debian based distributions ship CUPS pre-configured this way. +This script can also discover networked printers via DNS-SD, independent of CUPS, +and produce exact .service files for them, allowing the printers to be announced +on different subnets by copying the .service files to /etc/avahi/services/ there. +This solves the problem of AirPrint printers not being availabe outside the +local subnet even though routing/NAT exists between subnets. + DNSSD has a limit of 255 Chars for a given txt-record, because of this the list of accepted pdl's will be truncated to fit. If you're curious to see which ones are trimmed out of the list run with the script with the verbose flag (--verbose) @@ -17,10 +23,34 @@ are trimmed out of the list run with the script with the verbose flag (--verbose If python-lxml is installed, .service files will be generated in a human readble format, I wasn't able to get minidom's version to work acceptably. +The git repository also contains airprint.convs, airprint.types and apple.types. These need +to be copied to the /usr/share/cups/mime folder. + +Copy the .service files generated by this script to /etc/avahi/services. + +Then restart both avahi and cups with +sudo service avahi-daemon restart +sudo service cups restart + +**Python Requirements:** +This script requires depends on the python-cups library, and optionally python-lxml to make pretty xml files. + +Debian/Ubuntu: +sudo apt-get install python-cups python-lxml + +CentOS: +sudo yum install system-config-printer-libs + + Usage: airprint-generate.py [options] Options: -h, --help show this help message and exit + -s, --dnssd Search for network printers using DNS-SD (requires + avahi) + -D DNSDOMAIN, --dnsdomain=DNSDOMAIN + DNS domain where printers are located. + -c, --cups Search CUPS for shared printers (requires CUPS) -H HOSTNAME, --host=HOSTNAME Hostname of CUPS server (optional) -P PORT, --port=PORT Port number of CUPS server @@ -29,4 +59,5 @@ Options: Directory to create service files -v, --verbose Print debugging information to STDERR -p PREFIX, --prefix=PREFIX - Prefix all files with this string \ No newline at end of file + Prefix all files with this string + -a, --admin Include the printer specified uri as the adminurl diff --git a/airprint-generate.py b/airprint-generate.py index 989f63b..669ea2a 100755 --- a/airprint-generate.py +++ b/airprint-generate.py @@ -20,9 +20,13 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*** +Discovery by DNS-SD: Copyright (c) 2013 Vidar Tysse +*** """ -import cups, os, optparse, re, urlparse +import os, optparse, re, urlparse import os.path from StringIO import StringIO @@ -45,6 +49,17 @@ except: raise 'Failed to find python libxml or elementtree, please install one of those or use python >= 2.5' +try: + import cups +except: + cups = None + +try: + import avahisearch +except: + avahisearch = None + + XML_TEMPLATE = """ @@ -55,7 +70,7 @@ txtvers=1 qtotal=1 Transparent=T - URF=none + URF=DM3 """ @@ -99,7 +114,8 @@ class AirPrintGenerate(object): def __init__(self, host=None, user=None, port=None, verbose=False, - directory=None, prefix='AirPrint-', adminurl=False): + directory=None, prefix='AirPrint-', adminurl=False, usecups=True, + useavahi=False, dnsdomain=None): self.host = host self.user = user self.port = port @@ -107,134 +123,186 @@ def __init__(self, host=None, user=None, port=None, verbose=False, self.directory = directory self.prefix = prefix self.adminurl = adminurl + self.usecups = usecups and cups + self.useavahi = useavahi and avahisearch + self.dnsdomain = dnsdomain if self.user: cups.setUser(self.user) def generate(self): - if not self.host: - conn = cups.Connection() - else: - if not self.port: - self.port = 631 - conn = cups.Connection(self.host, self.port) + collected_printers = list() + + # Collect shared printers from CUPS if applicable + if self.usecups: + if self.verbose: + sys.stderr.write('Collecting shared printers from CUPS%s' % os.linesep) + if not self.host: + conn = cups.Connection() + else: + if not self.port: + self.port = 631 + conn = cups.Connection(self.host, self.port) - printers = conn.getPrinters() + printers = conn.getPrinters() - for p, v in printers.items(): - if v['printer-is-shared']: - attrs = conn.getPrinterAttributes(p) - uri = urlparse.urlparse(v['printer-uri-supported']) - - tree = ElementTree() - tree.parse(StringIO(XML_TEMPLATE.replace('\n', '').replace('\r', '').replace('\t', ''))) - - name = tree.find('name') - name.text = 'AirPrint %s @ %%h' % (p) - - service = tree.find('service') - - port = service.find('port') - port_no = None - if hasattr(uri, 'port'): - port_no = uri.port - if not port_no: - port_no = self.port - if not port_no: - port_no = cups.getPort() - port.text = '%d' % port_no - - if hasattr(uri, 'path'): - rp = uri.path - else: - rp = uri[2] - - re_match = re.match(r'^//(.*):(\d+)(/.*)', rp) - if re_match: - rp = re_match.group(3) + for p, v in printers.items(): + if v['printer-is-shared']: + attrs = conn.getPrinterAttributes(p) + uri = urlparse.urlparse(v['printer-uri-supported']) + + port_no = None + if hasattr(uri, 'port'): + port_no = uri.port + if not port_no: + port_no = self.port + if not port_no: + port_no = cups.getPort() + + if hasattr(uri, 'path'): + rp = uri.path + else: + rp = uri[2] - #Remove leading slashes from path - #TODO XXX FIXME I'm worried this will match broken urlparse - #results as well (for instance if they don't include a port) - #the xml would be malform'd either way - rp = re.sub(r'^/+', '', rp) + re_match = re.match(r'^//(.*):(\d+)(/.*)', rp) + if re_match: + rp = re_match.group(3) - path = Element('txt-record') - path.text = 'rp=%s' % (rp) - service.append(path) - - desc = Element('txt-record') - desc.text = 'note=%s' % (v['printer-info']) - service.append(desc) - - product = Element('txt-record') - product.text = 'product=(GPL Ghostscript)' - service.append(product) - - state = Element('txt-record') - state.text = 'printer-state=%s' % (v['printer-state']) - service.append(state) - - ptype = Element('txt-record') - ptype.text = 'printer-type=%s' % (hex(v['printer-type'])) - service.append(ptype) - - pdl = Element('txt-record') - fmts = [] - defer = [] - - for a in attrs['document-format-supported']: - if a in DOCUMENT_TYPES: - if DOCUMENT_TYPES[a]: - fmts.append(a) - else: - defer.append(a) + #Remove leading slashes from path + #TODO XXX FIXME I'm worried this will match broken urlparse + #results as well (for instance if they don't include a port) + #the xml would be malform'd either way + rp = re.sub(r'^/+', '', rp) + + pdl = Element('txt-record') + fmts = [] + defer = [] + + for a in attrs['document-format-supported']: + if a in DOCUMENT_TYPES: + if DOCUMENT_TYPES[a]: + fmts.append(a) + else: + defer.append(a) + + if 'image/urf' not in fmts: + sys.stderr.write('image/urf is not in mime types, %s may not be available on ios6 (see https://github.com/tjfontaine/airprint-generate/issues/5)%s' % (p, os.linesep)) + + fmts = ','.join(fmts+defer) + + dropped = [] + + # TODO XXX FIXME all fields should be checked for 255 limit + while len('pdl=%s' % (fmts)) >= 255: + (fmts, drop) = fmts.rsplit(',', 1) + dropped.append(drop) + + if len(dropped) and self.verbose: + sys.stderr.write('%s Losing support for: %s%s' % (p, ','.join(dropped), os.linesep)) + + collected_printers.append( { + 'SOURCE' : 'CUPS', + 'name' : p, + 'host' : None, # Could/should use self.host, but would break old behaviour + 'address' : None, + 'port' : port_no, + 'domain' : 'local', + 'txt' : { + 'txtvers' : '1', + 'qtotal' : '1', + 'Transparent' : 'T', + 'URF' : 'none', + 'rp' : rp, + 'note' : v['printer-info'], + 'product' : '(GPL Ghostscript)', + 'printer-state' : v['printer-state'], + 'printer-type' : v['printer-type'], + 'adminurl' : v['printer-uri-supported'], + 'pdl' : fmts, + } + } ) + + # Collect networked printers using DNS-SD if applicable + if (self.useavahi): + if self.verbose: + sys.stderr.write('Collecting networked printers using DNS-SD%s' % os.linesep) + finder = avahisearch.AvahiPrinterFinder(verbose=self.verbose) + for p in finder.Search(): + p['SOURCE'] = 'DNS-SD' + collected_printers.append(p) + + # Produce a .service file for each printer found + for p in collected_printers: + self.produce_settings_file(p) - if 'image/urf' not in fmts: - sys.stderr.write('image/urf is not in mime types, %s may not be available on ios6 (see https://github.com/tjfontaine/airprint-generate/issues/5)%s' % (p, os.linesep)) + def produce_settings_file(self, printer): + printer_name = printer['name'] + + tree = ElementTree() + tree.parse(StringIO(XML_TEMPLATE.replace('\n', '').replace('\r', '').replace('\t', ''))) - fmts = ','.join(fmts+defer) + name_node = tree.find('name') + name_node.text = 'AirPrint %s @ %%h' % printer_name - dropped = [] + service_node = tree.find('service') - # TODO XXX FIXME all fields should be checked for 255 limit - while len('pdl=%s' % (fmts)) >= 255: - (fmts, drop) = fmts.rsplit(',', 1) - dropped.append(drop) + port_node = service_node.find('port') + port_node.text = '%d' % printer['port'] + + host = printer['host'] + if host: + if self.dnsdomain: + pair = host.rsplit('.', 1) + if len(pair) > 1: + host = '.'.join((pair[0], self.dnsdomain)) + service_node.append(self.new_node('host-name', host)) + + txt = printer['txt'] + for key in txt: + if self.adminurl or key != 'adminurl': + service_node.append(self.new_txtrecord_node('%s=%s' % (key, txt[key]))) + + source = printer['SOURCE'] if printer.has_key('SOURCE') else '' + + fname = '%s%s%s.service' % (self.prefix, '%s-' % source if len(source) > 0 else '', printer_name) + + if self.directory: + fname = os.path.join(self.directory, fname) + + f = open(fname, 'w') - if len(dropped) and self.verbose: - sys.stderr.write('%s Losing support for: %s%s' % (p, ','.join(dropped), os.linesep)) + if etree: + tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8") + else: + xmlstr = tostring(tree.getroot()) + doc = parseString(xmlstr) + dt= minidom.getDOMImplementation('').createDocumentType('service-group', None, 'avahi-service.dtd') + doc.insertBefore(dt, doc.documentElement) + doc.writexml(f) + f.close() + + if self.verbose: + src = source if len(source) > 0 else 'unknown' + sys.stderr.write('Created from %s: %s%s' % (src, fname, os.linesep)) - pdl.text = 'pdl=%s' % (fmts) - service.append(pdl) + def new_txtrecord_node(self, text): + return self.new_node('txt-record', text) + + def new_node(self, tag, text): + element = Element(tag) + element.text = text + return element - if self.adminurl: - admin = Element('txt-record') - admin.text = 'adminurl=%s' % (v['printer-uri-supported']) - service.append(admin) - - fname = '%s%s.service' % (self.prefix, p) - - if self.directory: - fname = os.path.join(self.directory, fname) - - f = open(fname, 'w') - - if etree: - tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8") - else: - xmlstr = tostring(tree.getroot()) - doc = parseString(xmlstr) - dt= minidom.getDOMImplementation('').createDocumentType('service-group', None, 'avahi-service.dtd') - doc.insertBefore(dt, doc.documentElement) - doc.writexml(f) - f.close() - - if self.verbose: - sys.stderr.write('Created: %s%s' % (fname, os.linesep)) if __name__ == '__main__': parser = optparse.OptionParser() + parser.add_option('-s', '--dnssd', action="store_true", dest="avahi", + help="Search for network printers using DNS-SD (requires avahi)") + parser.add_option('-D', '--dnsdomain', action="store", type="string", + dest='dnsdomain', help='DNS domain where printers are located.', + metavar='DNSDOMAIN') + parser.add_option('-c', '--cups', action="store_true", dest="cups", + help="Search CUPS for shared printers (requires CUPS)") parser.add_option('-H', '--host', action="store", type="string", dest='hostname', help='Hostname of CUPS server (optional)', metavar='HOSTNAME') parser.add_option('-P', '--port', action="store", type="int", @@ -255,10 +323,19 @@ def generate(self): (options, args) = parser.parse_args() - # TODO XXX FIXME -- if cups login required, need to add - # air=username,password - from getpass import getpass - cups.setPasswordCB(getpass) + if not (options.cups and cups) and not (options.avahi and avahisearch): + sys.stderr.write('Nothing do do: --cups and/or --dnssd must be specified, and CUPS and/or avahi must be installed.%s' % os.linesep) + os._exit(1) + if options.cups and not cups: + sys.stderr.write('Warning: CUPS is not available. Ignoring --cups option.%s' % os.linesep) + if options.avahi and not avahisearch: + sys.stderr.write('Warning: Module avahisearch is not available. Ignoring --dnssd option.%s' % os.linesep) + + if options.cups and cups: + # TODO XXX FIXME -- if cups login required, need to add + # air=username,password + from getpass import getpass + cups.setPasswordCB(getpass) if options.directory: if not os.path.exists(options.directory): @@ -272,6 +349,12 @@ def generate(self): directory=options.directory, prefix=options.prefix, adminurl=options.adminurl, + usecups=options.cups, + useavahi=options.avahi, + dnsdomain=options.dnsdomain, ) apg.generate() + + if options.avahi and avahisearch and not options.dnsdomain: + sys.stderr.write("NOTE: If a printer found by DNS-SD do not resolve outside the local subnet, specify the printers' DNS domain with --dnsdomain or edit the generated element to fit your network.%s" % os.linesep) diff --git a/airprint.convs b/airprint.convs new file mode 100755 index 0000000..9bd2b93 --- /dev/null +++ b/airprint.convs @@ -0,0 +1,17 @@ +# +# "$Id: $" +# +# AirPrint +#leave it to others to fine tune this list +# not sure of all these are needed and 100 as priority might conflict with others +# +application/vnd.cups-raster image/urf 100 rastertourf +application/pdf image/urf 100 pdftoraster +# next line is need for generate.py and might be the only one needed +# will try later maybe myself +image/urf application/pdf 100 pdftoraster +application/vnd.apple-postscript image/urf 250 pstocupsraster +application/vnd.cups-postscript image/urf 250 pstocupsraster +# +# End of "$Id: $". +# diff --git a/airprint.types b/airprint.types new file mode 100755 index 0000000..88370bc --- /dev/null +++ b/airprint.types @@ -0,0 +1,8 @@ +# +# "$Id: $" +# +# AirPrint type +image/urf urf string(0,UNIRAST<00>) +# +# End of "$Id: $". +# diff --git a/apple.types b/apple.types new file mode 100755 index 0000000..440f34e --- /dev/null +++ b/apple.types @@ -0,0 +1 @@ +image/urf urf (0,UNIRAST) diff --git a/avahisearch.py b/avahisearch.py new file mode 100755 index 0000000..d05b062 --- /dev/null +++ b/avahisearch.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python + +""" +Search for printers that are announced over DNS-SD (aka Bonjour, Zeroconf, mDNS). + +Use standalone to show DNS-SD printer properties. +Use as module to enumerate DNS-SD printers in your own code. + +Used by a modified 'airprint-generate.py' to generate avahi .service files for +networked printers, allowing the printers to be announced on different subnets +by copying the .service files to /etc/avahi/services/ there. +This solves the problem of AirPrint printers not being availabe outside the +local subnet even though routing/NAT exists between subnets. + +Copyright (c) 2013 Vidar Tysse +Licence: Unlimited use is allowed. Including this copyright notice is requested. +""" + +import optparse + +import dbus, gobject, avahi +from dbus import DBusException +from dbus.mainloop.glib import DBusGMainLoop + +class AvahiPrinterFinder(object): + def __init__(self, ipv4_only=True, search_domain='local', verbose=False): + self.search_protocol = avahi.PROTO_INET if ipv4_only else avahi.PROTO_UNSPEC + self.search_domain = search_domain + self.verbose = verbose + self.service_type = '_ipp._tcp' # Look for network printers + self.still_receiving_events = 0 + self.printers = list() + + def ItemNew_handler(self, interface, protocol, name, stype, domain, flags): + self.still_receiving_events = 1 + if self.verbose: print "Found service '%s' type '%s' domain '%s' " % (name, stype, domain) + r_interface, r_protocol, r_name, r_stype, r_domain, r_host, r_aprotocol, r_address, r_port, r_txt, r_flags = \ + self.server.ResolveService( + interface, protocol, name, stype, domain, + self.search_protocol, dbus.UInt32(0) + ) + if self.verbose: print "RESOLVED: ", r_host, "-", r_name, "-", r_address, "-", r_port, "-", r_domain + self.printers.append( + dict( + host = str(r_host), + name = str(r_name), + address = str(r_address), + port = int(r_port), + domain = str(r_domain), + txt = self.txtarray_to_dict(avahi.txt_array_to_string_array(r_txt)) + ) + ) + + def AllForNow_handler(self): + if self.verbose: print "Finishing on AllForNow." + self.main_loop.quit() + + def timer_tick(self): + if not self.still_receiving_events: + if self.verbose: print "Finishing on timeout." + self.main_loop.quit() + return False; + self.still_receiving_events = 0 # If still 0 on next call, we assume we're done + return True + + def txtarray_to_dict(self, txtarray): + txtdict = dict() + for txt in txtarray: + pair = txt.split('=', 1) + txtdict[pair[0]] = '' if len(pair) < 2 else str(pair[1]) + return txtdict + + def Search(self): + loop = DBusGMainLoop() + + bus = dbus.SystemBus(mainloop=loop) + + self.server = dbus.Interface( bus.get_object(avahi.DBUS_NAME, '/'), + 'org.freedesktop.Avahi.Server') + + sbrowser = dbus.Interface(bus.get_object(avahi.DBUS_NAME, + self.server.ServiceBrowserNew(avahi.IF_UNSPEC, + self.search_protocol, self.service_type, self.search_domain, dbus.UInt32(0))), + avahi.DBUS_INTERFACE_SERVICE_BROWSER) + + sbrowser.connect_to_signal("ItemNew", self.ItemNew_handler) + sbrowser.connect_to_signal("AllForNow", self.AllForNow_handler) + + gobject.timeout_add(2000, self.timer_tick) + + self.main_loop = gobject.MainLoop() + self.main_loop.run() + return self.printers + + +if __name__ == '__main__': + parser = optparse.OptionParser() + parser.add_option('-v', '--verbose', action="store_true", dest="verbose", + help="Print debugging information") + (options, args) = parser.parse_args() + + finder = AvahiPrinterFinder(verbose=options.verbose) + printers = finder.Search() + for p in printers: + print + print p['name'] + print " host = %s" % p['host'] + print " address = %s" % p['address'] + print " port = %s" % p['port'] + print " domain = %s" % p['domain'] + print " txt record:" + for key in p['txt']: + print " %s = %s" % (key, p['txt'][key]) + print