├── config └── .gitkeep ├── services └── .gitkeep ├── spool └── .gitkeep ├── .env ├── docker-compose.yaml ├── printer-update.sh ├── start-cups.sh ├── Dockerfile ├── README.md └── airprint-generate.py /config/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /services/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spool/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | CUPSADMIN=cups 2 | CUPSPASSWORD=s3cret 3 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | aircups: 4 | container_name: aircups 5 | image: maxandersen/aircups 6 | volumes: 7 | - ./config:/config 8 | - ./spool:/var/spool/cups-pdf 9 | #- ./services:/services 10 | - /etc/avahi/services:/services 11 | 12 | restart: always 13 | environment: 14 | CUPSADMIN: "${CUPSADMIN}" 15 | CUPSPASSWORD: "${CUPSPASSWORD}" 16 | expose: 17 | - 631 18 | ports: 19 | - 631:631 -------------------------------------------------------------------------------- /printer-update.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | /usr/bin/inotifywait -m -e close_write,moved_to,create /etc/cups | 3 | while read -r directory events filename; do 4 | if [ "$filename" = "printers.conf" ]; then 5 | echo "printers.conf changed. Deleteting (if any) old airprint services." 6 | rm -rf /services/AirPrint-*.service 7 | echo "Generating airprint services for all shared printers" 8 | ./airprint-generate.py -d /services 9 | cp /etc/cups/printers.conf /config/printers.conf 10 | #rsync -avh /services/ /etc/avahi/services/ 11 | echo "Completed update." 12 | else 13 | echo "printers.conf not changed" 14 | fi 15 | done 16 | -------------------------------------------------------------------------------- /start-cups.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | set -x 4 | 5 | if [ $(grep -ci $CUPSADMIN /etc/shadow) -eq 0 ]; then 6 | adduser -S -G lpadmin --no-create-home $CUPSADMIN 7 | fi 8 | echo $CUPSADMIN:$CUPSPASSWORD | chpasswd 9 | 10 | mkdir -p /config/ppd 11 | mkdir -p /services 12 | rm -rf /etc/cups/ppd 13 | ln -s /config/ppd /etc/cups 14 | #if [ `ls -l /services/*.service 2>/dev/null | wc -l` -gt 0 ]; then 15 | # cp -f /services/*.service /etc/avahi/services/ 16 | #fi 17 | if [ `ls -l /config/printers.conf 2>/dev/null | wc -l` -eq 0 ]; then 18 | touch /config/printers.conf 19 | fi 20 | cp /config/printers.conf /etc/cups/printers.conf 21 | 22 | #/usr/sbin/avahi-daemon --daemonize 23 | ./printer-update.sh & 24 | sleep 1 25 | touch /etc/cups/printers.conf 26 | exec /usr/sbin/cupsd -f -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:edge 2 | 3 | MAINTAINER Ann Arbor District Library 4 | 5 | RUN apk add --update --no-cache --repository=https://s3.amazonaws.com/aadl-github/alpine \ 6 | cups-pdf cups-filters 'cups<2.2.7' --allow-untrusted 7 | 8 | RUN apk add --update --no-cache --repository=http://nl.alpinelinux.org/alpine/edge/testing hplip rsync inotify-tools python python-dev musl-dev cups-dev gcc py-pip --allow-untrusted 9 | 10 | RUN pip install pycups 11 | 12 | RUN \ 13 | sed -i 's/Listen localhost:631/Listen 0.0.0.0:631/' /etc/cups/cupsd.conf && \ 14 | sed -i 's//\n Allow All/' /etc/cups/cupsd.conf && \ 15 | sed -i 's//\n Allow All\n Require user @SYSTEM/' /etc/cups/cupsd.conf && \ 16 | sed -i 's//\n Allow All/' /etc/cups/cupsd.conf && \ 17 | echo "ServerAlias *" >> /etc/cups/cupsd.conf && \ 18 | echo "DefaultEncryption Never" >> /etc/cups/cupsd.conf && \ 19 | echo "DirtyCleanInterval 5" >> /etc/cups/cupsd.conf 20 | 21 | VOLUME /etc/cups/ /var/log/cups /var/spool/cups /var/spool/cups-pdf /var/cache/cups 22 | 23 | COPY start-cups.sh /root/start-cups.sh 24 | COPY airprint-generate.py /root/airprint-generate.py 25 | COPY printer-update.sh /root/printer-update.sh 26 | 27 | 28 | WORKDIR /root 29 | RUN chmod +x start-cups.sh 30 | RUN chmod +x printer-update.sh 31 | RUN chmod +x airprint-generate.py 32 | 33 | CMD ["/root/start-cups.sh"] 34 | 35 | EXPOSE 631 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # maxandersen/aircups 2 | 3 | This Alpine-based Docker image runs a CUPS instance that is meant as an AirPrint relay for printers that are already on the network but not AirPrint capable. The other images out there never seemed to work right. I forked the original to use Alpine instead of Ubuntu and work on more host OS's. 4 | 5 | ## Configuration 6 | 7 | ### Volumes: 8 | * `/config`: where the persistent printer configs will be stored 9 | * `/services`: where the Avahi service files will be generated 10 | * `/var/spool/cups-pdf`: where cups-pdf will put pdf files 11 | 12 | ### Variables: 13 | * `CUPSADMIN`: the CUPS admin user you want created 14 | * `CUPSPASSWORD`: the password for the CUPS admin user 15 | 16 | ### Example run command: 17 | ``` 18 | docker run --name cups --restart unless-stopped --net host\ 19 | -v :/services \ 20 | -v :/config \ 21 | -v :/var/spool/cups-pdf \ 22 | -e CUPSADMIN="" \ 23 | -e CUPSPASSWORD="" \ 24 | maxandersen/aircups:latest 25 | ``` 26 | 27 | ## Add and set up printer: 28 | * CUPS will be configurable at http://[host ip]:631 using the CUPSADMIN/CUPSPASSWORD. 29 | * Make sure you select `Share This Printer` when configuring the printer in CUPS. 30 | * ***After configuring your printer, you need to close the web browser for at least 60 seconds. CUPS will not write the config files until it detects the connection is closed for as long as a minute.*** 31 | 32 | ## Acknowledgements 33 | 34 | Based on work of [quadportnick/docker-cups-airprint](https://github.com/quadportnick/docker-cups-airprint), https://github.com/chuckcharlie/cups-avahi-airprint and 35 | especially https://github.com/aadl/docker-cups-alpine which had the only working out of box cups-pdf I could find. 36 | -------------------------------------------------------------------------------- /airprint-generate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Copyright (c) 2010 Timothy J Fontaine 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | """ 24 | 25 | import cups, os, optparse, re, urlparse 26 | import os.path 27 | from StringIO import StringIO 28 | 29 | from xml.dom.minidom import parseString 30 | from xml.dom import minidom 31 | 32 | import sys 33 | 34 | try: 35 | import lxml.etree as etree 36 | from lxml.etree import Element, ElementTree, tostring 37 | except: 38 | try: 39 | from xml.etree.ElementTree import Element, ElementTree, tostring 40 | etree = None 41 | except: 42 | try: 43 | from elementtree import Element, ElementTree, tostring 44 | etree = None 45 | except: 46 | raise 'Failed to find python libxml or elementtree, please install one of those or use python >= 2.5' 47 | 48 | XML_TEMPLATE = """ 49 | 50 | 51 | 52 | _ipp._tcp 53 | _universal._sub._ipp._tcp 54 | 631 55 | txtvers=1 56 | qtotal=1 57 | Transparent=T 58 | URF=none 59 | 60 | """ 61 | 62 | #TODO XXX FIXME 63 | #ty=AirPrint Ricoh Aficio MP 6000 64 | #Binary=T 65 | #Duplex=T 66 | #Copies=T 67 | 68 | 69 | DOCUMENT_TYPES = { 70 | # These content-types will be at the front of the list 71 | 'application/pdf': True, 72 | 'application/postscript': True, 73 | 'application/vnd.cups-raster': True, 74 | 'application/octet-stream': True, 75 | 'image/urf': True, 76 | 'image/png': True, 77 | 'image/tiff': True, 78 | 'image/png': True, 79 | 'image/jpeg': True, 80 | 'image/gif': True, 81 | 'text/plain': True, 82 | 'text/html': True, 83 | 84 | # These content-types will never be reported 85 | 'image/x-xwindowdump': False, 86 | 'image/x-xpixmap': False, 87 | 'image/x-xbitmap': False, 88 | 'image/x-sun-raster': False, 89 | 'image/x-sgi-rgb': False, 90 | 'image/x-portable-pixmap': False, 91 | 'image/x-portable-graymap': False, 92 | 'image/x-portable-bitmap': False, 93 | 'image/x-portable-anymap': False, 94 | 'application/x-shell': False, 95 | 'application/x-perl': False, 96 | 'application/x-csource': False, 97 | 'application/x-cshell': False, 98 | } 99 | 100 | class AirPrintGenerate(object): 101 | def __init__(self, host=None, user=None, port=None, verbose=False, 102 | directory=None, prefix='AirPrint-', adminurl=False): 103 | self.host = host 104 | self.user = user 105 | self.port = port 106 | self.verbose = verbose 107 | self.directory = directory 108 | self.prefix = prefix 109 | self.adminurl = adminurl 110 | 111 | if self.user: 112 | cups.setUser(self.user) 113 | 114 | def generate(self): 115 | if not self.host: 116 | conn = cups.Connection() 117 | else: 118 | if not self.port: 119 | self.port = 631 120 | conn = cups.Connection(self.host, self.port) 121 | 122 | printers = conn.getPrinters() 123 | 124 | for p, v in printers.items(): 125 | if v['printer-is-shared']: 126 | attrs = conn.getPrinterAttributes(p) 127 | uri = urlparse.urlparse(v['printer-uri-supported']) 128 | 129 | tree = ElementTree() 130 | tree.parse(StringIO(XML_TEMPLATE.replace('\n', '').replace('\r', '').replace('\t', ''))) 131 | 132 | name = tree.find('name') 133 | name.text = 'AirPrint %s @ %%h' % (p) 134 | 135 | service = tree.find('service') 136 | 137 | port = service.find('port') 138 | port_no = None 139 | if hasattr(uri, 'port'): 140 | port_no = uri.port 141 | if not port_no: 142 | port_no = self.port 143 | if not port_no: 144 | port_no = cups.getPort() 145 | port.text = '%d' % port_no 146 | 147 | if hasattr(uri, 'path'): 148 | rp = uri.path 149 | else: 150 | rp = uri[2] 151 | 152 | re_match = re.match(r'^//(.*):(\d+)(/.*)', rp) 153 | if re_match: 154 | rp = re_match.group(3) 155 | 156 | #Remove leading slashes from path 157 | #TODO XXX FIXME I'm worried this will match broken urlparse 158 | #results as well (for instance if they don't include a port) 159 | #the xml would be malform'd either way 160 | rp = re.sub(r'^/+', '', rp) 161 | 162 | path = Element('txt-record') 163 | path.text = 'rp=%s' % (rp) 164 | service.append(path) 165 | 166 | desc = Element('txt-record') 167 | desc.text = 'note=%s' % (v['printer-info']) 168 | service.append(desc) 169 | 170 | product = Element('txt-record') 171 | product.text = 'product=(GPL Ghostscript)' 172 | service.append(product) 173 | 174 | state = Element('txt-record') 175 | state.text = 'printer-state=%s' % (v['printer-state']) 176 | service.append(state) 177 | 178 | ptype = Element('txt-record') 179 | ptype.text = 'printer-type=%s' % (hex(v['printer-type'])) 180 | service.append(ptype) 181 | 182 | pdl = Element('txt-record') 183 | fmts = [] 184 | defer = [] 185 | 186 | for a in attrs['document-format-supported']: 187 | if a in DOCUMENT_TYPES: 188 | if DOCUMENT_TYPES[a]: 189 | fmts.append(a) 190 | else: 191 | defer.append(a) 192 | 193 | if 'image/urf' not in fmts: 194 | 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)) 195 | 196 | fmts = ','.join(fmts+defer) 197 | 198 | dropped = [] 199 | 200 | # TODO XXX FIXME all fields should be checked for 255 limit 201 | while len('pdl=%s' % (fmts)) >= 255: 202 | (fmts, drop) = fmts.rsplit(',', 1) 203 | dropped.append(drop) 204 | 205 | if len(dropped) and self.verbose: 206 | sys.stderr.write('%s Losing support for: %s%s' % (p, ','.join(dropped), os.linesep)) 207 | 208 | pdl.text = 'pdl=%s' % (fmts) 209 | service.append(pdl) 210 | 211 | if self.adminurl: 212 | admin = Element('txt-record') 213 | admin.text = 'adminurl=%s' % (v['printer-uri-supported']) 214 | service.append(admin) 215 | 216 | fname = '%s%s.service' % (self.prefix, p) 217 | 218 | if self.directory: 219 | fname = os.path.join(self.directory, fname) 220 | 221 | f = open(fname, 'w') 222 | 223 | if etree: 224 | tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8") 225 | else: 226 | xmlstr = tostring(tree.getroot()) 227 | doc = parseString(xmlstr) 228 | dt= minidom.getDOMImplementation('').createDocumentType('service-group', None, 'avahi-service.dtd') 229 | doc.insertBefore(dt, doc.documentElement) 230 | doc.writexml(f) 231 | f.close() 232 | 233 | if self.verbose: 234 | sys.stderr.write('Created: %s%s' % (fname, os.linesep)) 235 | 236 | if __name__ == '__main__': 237 | parser = optparse.OptionParser() 238 | parser.add_option('-H', '--host', action="store", type="string", 239 | dest='hostname', help='Hostname of CUPS server (optional)', metavar='HOSTNAME') 240 | parser.add_option('-P', '--port', action="store", type="int", 241 | dest='port', help='Port number of CUPS server', metavar='PORT') 242 | parser.add_option('-u', '--user', action="store", type="string", 243 | dest='username', help='Username to authenticate with against CUPS', 244 | metavar='USER') 245 | parser.add_option('-d', '--directory', action="store", type="string", 246 | dest='directory', help='Directory to create service files', 247 | metavar='DIRECTORY') 248 | parser.add_option('-v', '--verbose', action="store_true", dest="verbose", 249 | help="Print debugging information to STDERR") 250 | parser.add_option('-p', '--prefix', action="store", type="string", 251 | dest='prefix', help='Prefix all files with this string', metavar='PREFIX', 252 | default='AirPrint-') 253 | parser.add_option('-a', '--admin', action="store_true", dest="adminurl", 254 | help="Include the printer specified uri as the adminurl") 255 | 256 | (options, args) = parser.parse_args() 257 | 258 | # TODO XXX FIXME -- if cups login required, need to add 259 | # air=username,password 260 | from getpass import getpass 261 | cups.setPasswordCB(getpass) 262 | 263 | if options.directory: 264 | if not os.path.exists(options.directory): 265 | os.mkdir(options.directory) 266 | 267 | apg = AirPrintGenerate( 268 | user=options.username, 269 | host=options.hostname, 270 | port=options.port, 271 | verbose=options.verbose, 272 | directory=options.directory, 273 | prefix=options.prefix, 274 | adminurl=options.adminurl, 275 | ) 276 | 277 | apg.generate() 278 | --------------------------------------------------------------------------------