]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - backend/usb-libusb.c
Merge pull request #5621 from zdohnal/cgigetarray-sigsegv
[thirdparty/cups.git] / backend / usb-libusb.c
index 5811fde1f0dfb3dd6a244efc0a079608e0201e27..1c4d9f11721d41df3a762a3177ca3f0fcaea0a40 100644 (file)
@@ -1,30 +1,10 @@
 /*
- * "$Id$"
+ * LIBUSB interface code for CUPS.
  *
- *   LIBUSB interface code for CUPS.
+ * Copyright 2007-2019 by Apple Inc.
  *
- *   Copyright 2007-2012 by Apple Inc.
- *
- *   These coded instructions, statements, and computer programs are the
- *   property of Apple Inc. and are protected by Federal copyright
- *   law.  Distribution and use rights are outlined in the file "LICENSE.txt"
- *   which should have been included with this file.  If this file is
- *   file is missing or damaged, see the license at "http://www.cups.org/".
- *
- * Contents:
- *
- *   list_devices()   - List the available printers.
- *   print_device()      - Print a file to a USB device.
- *   close_device()      - Close the connection to the USB printer.
- *   find_device()       - Find or enumerate USB printers.
- *   get_device_id()     - Get the IEEE-1284 device ID for the printer.
- *   list_cb()           - List USB printers for discovery.
- *   make_device_uri()   - Create a device URI for a USB printer.
- *   open_device()       - Open a connection to the USB printer.
- *   print_cb()          - Find a USB printer for printing.
- *   read_thread()       - Thread to read the backchannel data on.
- *   sidechannel_thread() - Handle side-channel requests.
- *   soft_reset()        - Send a soft reset to the device.
+ * Licensed under Apache License v2.0.  See the file "LICENSE" for more
+ * information.
  */
 
 /*
@@ -33,6 +13,8 @@
 
 #include <libusb.h>
 #include <cups/cups-private.h>
+#include <cups/ppd-private.h>
+#include <cups/dir.h>
 #include <pthread.h>
 #include <sys/select.h>
 #include <sys/types.h>
@@ -60,20 +42,22 @@ typedef struct usb_printer_s                /**** USB Printer Data ****/
 {
   struct libusb_device *device;        /* Device info */
   int                  conf,           /* Configuration */
+                       origconf,       /* Original configuration */
                        iface,          /* Interface */
                        altset,         /* Alternate setting */
                        write_endp,     /* Write endpoint */
-                        read_endp,     /* Read endpoint */
+                       read_endp,      /* Read endpoint */
                        protocol,       /* Protocol: 1 = Uni-di, 2 = Bi-di. */
-                        usblp_attached; /* Is the "usblp" kernel module
-                                          attached? */
+                       usblp_attached, /* "usblp" kernel module attached? */
+                       reset_after_job;/* Set to 1 by print_device() */
+  unsigned             quirks;         /* Quirks flags */
   struct libusb_device_handle *handle; /* Open handle to device */
 } usb_printer_t;
 
 typedef int (*usb_cb_t)(usb_printer_t *, const char *, const char *,
                         const void *);
 
-typedef struct usb_globals_s
+typedef struct usb_globals_s           /* Global USB printer information */
 {
   usb_printer_t                *printer;       /* Printer */
 
@@ -99,13 +83,43 @@ typedef struct usb_globals_s
   int                  sidechannel_thread_done;
 } usb_globals_t;
 
+/*
+ * Quirks: various printer quirks are handled by this structure and its flags.
+ *
+ * The quirks table used to be compiled into the backend but is now loaded from
+ * one or more files in the /usr/share/cups/usb directory.
+ */
+
+#define USB_QUIRK_BLACKLIST    0x0001  /* Does not conform to the spec */
+#define USB_QUIRK_NO_REATTACH  0x0002  /* After printing we cannot re-attach
+                                          the usblp kernel module */
+#define USB_QUIRK_SOFT_RESET   0x0004  /* After printing do a soft reset
+                                          for clean-up */
+#define USB_QUIRK_UNIDIR       0x0008  /* Requires unidirectional mode */
+#define USB_QUIRK_USB_INIT     0x0010  /* Needs vendor USB init string */
+#define USB_QUIRK_VENDOR_CLASS 0x0020  /* Descriptor uses vendor-specific
+                                          Class or SubClass */
+#define USB_QUIRK_DELAY_CLOSE  0x0040  /* Delay close */
+#define USB_QUIRK_WHITELIST    0x0000  /* no quirks */
+
+
+typedef struct usb_quirk_s             /* USB "quirk" information */
+{
+  int          vendor_id,              /* Affected vendor ID */
+               product_id;             /* Affected product ID or 0 for all */
+  unsigned     quirks;                 /* Quirks bitfield */
+} usb_quirk_t;
+
+
+
 
 /*
  * Globals...
  */
 
+cups_array_t           *all_quirks;    /* Array of printer quirks */
 usb_globals_t          g = { 0 };      /* Globals */
-libusb_device           **list;         /* List of connected USB devices */
+libusb_device          **all_list;     /* List of connected USB devices */
 
 
 /*
@@ -113,11 +127,14 @@ libusb_device           **list;         /* List of connected USB devices */
  */
 
 static int             close_device(usb_printer_t *printer);
+static int             compare_quirks(usb_quirk_t *a, usb_quirk_t *b);
 static usb_printer_t   *find_device(usb_cb_t cb, const void *data);
+static unsigned                find_quirks(int vendor_id, int product_id);
 static int             get_device_id(usb_printer_t *printer, char *buffer,
                                      size_t bufsize);
 static int             list_cb(usb_printer_t *printer, const char *device_uri,
                                const char *device_id, const void *data);
+static void            load_quirks(void);
 static char            *make_device_uri(usb_printer_t *printer,
                                         const char *device_id,
                                         char *uri, size_t uri_size);
@@ -127,6 +144,7 @@ static int          print_cb(usb_printer_t *printer, const char *device_uri,
 static void            *read_thread(void *reference);
 static void            *sidechannel_thread(void *reference);
 static void            soft_reset(void);
+static int             soft_reset_printer(usb_printer_t *printer);
 
 
 /*
@@ -136,6 +154,8 @@ static void         soft_reset(void);
 void
 list_devices(void)
 {
+  load_quirks();
+
   fputs("DEBUG: list_devices\n", stderr);
   find_device(list_cb, NULL);
 }
@@ -163,7 +183,8 @@ print_device(const char *uri,               /* I - Device URI */
                iostatus;               /* Current IO status */
   pthread_t    read_thread_id,         /* Read thread */
                sidechannel_thread_id;  /* Side-channel thread */
-  int          have_sidechannel = 0;   /* Was the side-channel thread started? */
+  int          have_sidechannel = 0,   /* Was the side-channel thread started? */
+               have_backchannel = 0;   /* Do we have a back channel? */
   struct stat   sidechannel_info;      /* Side-channel file descriptor info */
   unsigned char        print_buffer[8192],     /* Print data buffer */
                *print_ptr;             /* Pointer into print data buffer */
@@ -172,8 +193,13 @@ print_device(const char *uri,              /* I - Device URI */
   struct timeval *timeout,             /* Timeout pointer */
                tv;                     /* Time value */
   struct timespec cond_timeout;                /* pthread condition timeout */
+  int          num_opts;               /* Number of options */
+  cups_option_t        *opts;                  /* Options */
+  const char   *val;                   /* Option value */
 
 
+  load_quirks();
+
  /*
   * See if the side-channel descriptor is valid...
   */
@@ -187,6 +213,7 @@ print_device(const char *uri,               /* I - Device URI */
   * Connect to the printer...
   */
 
+  fprintf(stderr, "DEBUG: Printing on printer with URI: %s\n", uri);
   while ((g.printer = find_device(print_cb, uri)) == NULL)
   {
     _cupsLangPrintFilter(stderr, "INFO",
@@ -196,6 +223,12 @@ print_device(const char *uri,              /* I - Device URI */
 
   g.print_fd = print_fd;
 
+ /*
+  * Some devices need a reset after finishing a job, these devices are
+  * marked with the USB_QUIRK_SOFT_RESET quirk.
+  */
+  g.printer->reset_after_job = (g.printer->quirks & USB_QUIRK_SOFT_RESET ? 1 : 0);
+
  /*
   * If we are printing data from a print driver on stdin, ignore SIGTERM
   * so that the driver can finish out any page data, e.g. to eject the
@@ -240,25 +273,62 @@ print_device(const char *uri,             /* I - Device URI */
   }
 
  /*
-  * Get the read thread going...
+  * Debug mode: If option "usb-unidir" is given, always deactivate
+  * backchannel
   */
 
-  g.read_thread_stop = 0;
-  g.read_thread_done = 0;
+  num_opts = cupsParseOptions(argv[5], 0, &opts);
+  val = cupsGetOption("usb-unidir", num_opts, opts);
+  if (val && strcasecmp(val, "no") && strcasecmp(val, "off") &&
+      strcasecmp(val, "false"))
+  {
+    g.printer->read_endp = -1;
+    fprintf(stderr, "DEBUG: Forced uni-directional communication "
+           "via \"usb-unidir\" option.\n");
+  }
 
-  pthread_cond_init(&g.read_thread_cond, NULL);
-  pthread_mutex_init(&g.read_thread_mutex, NULL);
+ /*
+  * Debug mode: If option "usb-no-reattach" is given, do not re-attach
+  * the usblp kernel module after the job has completed.
+  */
 
-  if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
+  val = cupsGetOption("usb-no-reattach", num_opts, opts);
+  if (val && strcasecmp(val, "no") && strcasecmp(val, "off") &&
+      strcasecmp(val, "false"))
   {
-    fprintf(stderr, "DEBUG: Fatal USB error.\n");
-    _cupsLangPrintFilter(stderr, "ERROR",
-                         _("There was an unrecoverable USB error."));
-    fputs("DEBUG: Couldn't create read thread.\n", stderr);
-    close_device(g.printer);
-    return (CUPS_BACKEND_STOP);
+    g.printer->usblp_attached = 0;
+    fprintf(stderr, "DEBUG: Forced not re-attaching the usblp kernel module "
+           "after the job via \"usb-no-reattach\" option.\n");
   }
 
+ /*
+  * Get the read thread going...
+  */
+
+  if (g.printer->read_endp != -1)
+  {
+    have_backchannel = 1;
+
+    g.read_thread_stop = 0;
+    g.read_thread_done = 0;
+
+    pthread_cond_init(&g.read_thread_cond, NULL);
+    pthread_mutex_init(&g.read_thread_mutex, NULL);
+
+    if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
+    {
+      fprintf(stderr, "DEBUG: Fatal USB error.\n");
+      _cupsLangPrintFilter(stderr, "ERROR",
+                          _("There was an unrecoverable USB error."));
+      fputs("DEBUG: Couldn't create read thread.\n", stderr);
+      close_device(g.printer);
+      return (CUPS_BACKEND_STOP);
+    }
+  }
+  else
+    fprintf(stderr, "DEBUG: Uni-directional device/mode, back channel "
+           "deactivated.\n");
+
  /*
   * The main thread sends the print file...
   */
@@ -403,7 +473,7 @@ print_device(const char *uri,               /* I - Device URI */
        iostatus = libusb_bulk_transfer(g.printer->handle,
                                        g.printer->write_endp,
                                        print_buffer, g.print_bytes,
-                                       &bytes, 60000);
+                                       &bytes, 0);
        /*
        * Ignore timeout errors, but retain the number of bytes written to
        * avoid sending duplicate data...
@@ -426,7 +496,7 @@ print_device(const char *uri,               /* I - Device URI */
          iostatus = libusb_bulk_transfer(g.printer->handle,
                                          g.printer->write_endp,
                                          print_buffer, g.print_bytes,
-                                         &bytes, 60000);
+                                         &bytes, 0);
        }
 
        /*
@@ -441,7 +511,7 @@ print_device(const char *uri,               /* I - Device URI */
          iostatus = libusb_bulk_transfer(g.printer->handle,
                                          g.printer->write_endp,
                                          print_buffer, g.print_bytes,
-                                         &bytes, 60000);
+                                         &bytes, 0);
         }
 
        if (iostatus)
@@ -515,38 +585,18 @@ print_device(const char *uri,             /* I - Device URI */
   * Signal the read thread to exit then wait 7 seconds for it to complete...
   */
 
-  g.read_thread_stop = 1;
-
-  pthread_mutex_lock(&g.read_thread_mutex);
-
-  if (!g.read_thread_done)
+  if (have_backchannel)
   {
-    fputs("DEBUG: Waiting for read thread to exit...\n", stderr);
-
-    gettimeofday(&tv, NULL);
-    cond_timeout.tv_sec  = tv.tv_sec + WAIT_EOF_DELAY;
-    cond_timeout.tv_nsec = tv.tv_usec * 1000;
-
-    while (!g.read_thread_done)
-    {
-      if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
-                                &cond_timeout) != 0)
-       break;
-    }
+    g.read_thread_stop = 1;
 
-   /*
-    * If it didn't exit abort the pending read and wait an additional second...
-    */
+    pthread_mutex_lock(&g.read_thread_mutex);
 
     if (!g.read_thread_done)
     {
-      fputs("DEBUG: Read thread still active, aborting the pending read...\n",
-           stderr);
-
-      g.wait_eof = 0;
+      fputs("DEBUG: Waiting for read thread to exit...\n", stderr);
 
       gettimeofday(&tv, NULL);
-      cond_timeout.tv_sec  = tv.tv_sec + 1;
+      cond_timeout.tv_sec  = tv.tv_sec + WAIT_EOF_DELAY;
       cond_timeout.tv_nsec = tv.tv_usec * 1000;
 
       while (!g.read_thread_done)
@@ -555,25 +605,49 @@ print_device(const char *uri,             /* I - Device URI */
                                   &cond_timeout) != 0)
          break;
       }
-    }
-  }
 
-  pthread_mutex_unlock(&g.read_thread_mutex);
+      /*
+       * If it didn't exit abort the pending read and wait an additional
+       * second...
+       */
+
+      if (!g.read_thread_done)
+      {
+       fputs("DEBUG: Read thread still active, aborting the pending read...\n",
+             stderr);
+
+       g.wait_eof = 0;
 
-  if (print_fd)
-    close(print_fd);
+       gettimeofday(&tv, NULL);
+       cond_timeout.tv_sec  = tv.tv_sec + 1;
+       cond_timeout.tv_nsec = tv.tv_usec * 1000;
+
+       while (!g.read_thread_done)
+       {
+         if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
+                                    &cond_timeout) != 0)
+           break;
+       }
+      }
+    }
+
+    pthread_mutex_unlock(&g.read_thread_mutex);
+  }
 
  /*
   * Close the connection and input file and general clean up...
   */
 
+  if (g.printer->quirks & USB_QUIRK_DELAY_CLOSE)
+    sleep(1);
+
   close_device(g.printer);
 
  /*
   * Clean up ....
   */
 
-  libusb_free_device_list(list, 1);
+  libusb_free_device_list(all_list, 1);
   libusb_exit(NULL);
 
   return (status);
@@ -600,31 +674,86 @@ close_device(usb_printer_t *printer)      /* I - Printer */
     * to the device...
     */
 
-    int number;                                /* Interface number */
+    int errcode;                       /* Return value of libusb function */
+    int number1,                       /* Interface number */
+       number2;                        /* Configuration number */
 
-    libusb_get_device_descriptor(printer->device, &devdesc);
-    libusb_get_config_descriptor(printer->device, printer->conf, &confptr);
-    number = confptr->interface[printer->iface].
-                 altsetting[printer->altset].bInterfaceNumber;
-    libusb_release_interface(printer->handle, number);
-    if (number != 0)
-      libusb_release_interface(printer->handle, 0);
+    errcode =
+      libusb_get_config_descriptor(printer->device, printer->conf, &confptr);
+    if (errcode >= 0)
+    {
+      number1 = confptr->interface[printer->iface].
+       altsetting[printer->altset].bInterfaceNumber;
+      libusb_release_interface(printer->handle, number1);
+
+      number2 = confptr->bConfigurationValue;
+
+      libusb_free_config_descriptor(confptr);
+
+     /*
+      * If we have changed the configuration from one valid configuration
+      * to another, restore the old one
+      */
+      if (printer->origconf > 0 && printer->origconf != number2)
+      {
+       fprintf(stderr, "DEBUG: Restoring USB device configuration: %d -> %d\n",
+               number2, printer->origconf);
+       if ((errcode = libusb_set_configuration(printer->handle,
+                                               printer->origconf)) < 0)
+       {
+         if (errcode != LIBUSB_ERROR_BUSY)
+         {
+           errcode =
+             libusb_get_device_descriptor (printer->device, &devdesc);
+           if (errcode < 0)
+             fprintf(stderr,
+                     "DEBUG: Failed to set configuration %d\n",
+                     printer->origconf);
+           else
+             fprintf(stderr,
+                     "DEBUG: Failed to set configuration %d for %04x:%04x\n",
+                     printer->origconf, devdesc.idVendor, devdesc.idProduct);
+         }
+       }
+      }
+
+     /*
+      * Re-attach "usblp" kernel module if it was attached before using this
+      * device
+      */
+      if (printer->usblp_attached == 1)
+       if (libusb_attach_kernel_driver(printer->handle, number1) < 0)
+       {
+         errcode = libusb_get_device_descriptor (printer->device, &devdesc);
+         if (errcode < 0)
+           fprintf(stderr,
+                   "DEBUG: Failed to re-attach \"usblp\" kernel module\n");
+         else
+           fprintf(stderr,
+                   "DEBUG: Failed to re-attach \"usblp\" kernel module to "
+                   "%04x:%04x\n", devdesc.idVendor, devdesc.idProduct);
+       }
+    }
+    else
+      fprintf(stderr,
+             "DEBUG: Failed to get configuration descriptor %d\n",
+             printer->conf);
 
    /*
-    * Re-attach "usblp" kernel module if it was attached before using this
-    * device
+    * Reset the device to clean up after the job
     */
 
-    if (printer->usblp_attached == 1)
+    if (printer->reset_after_job == 1)
     {
-      if (libusb_attach_kernel_driver(printer->handle, printer->iface) < 0)
+      if ((errcode = libusb_reset_device(printer->handle)) < 0)
        fprintf(stderr,
-               "DEBUG: Failed to re-attach \"usblp\" kernel module to "
-               "%04x:%04x\n", devdesc.idVendor, devdesc.idProduct);
+               "DEBUG: Device reset failed, error code: %d\n",
+               errcode);
+      else
+       fprintf(stderr,
+               "DEBUG: Resetting printer.\n");
     }
 
-    libusb_free_config_descriptor(confptr);
-
    /*
     * Close the interface and return...
     */
@@ -637,6 +766,23 @@ close_device(usb_printer_t *printer)       /* I - Printer */
 }
 
 
+/*
+ * 'compare_quirks()' - Compare two quirks entries.
+ */
+
+static int                             /* O - Result of comparison */
+compare_quirks(usb_quirk_t *a,         /* I - First quirk entry */
+               usb_quirk_t *b)         /* I - Second quirk entry */
+{
+  int result;                          /* Result of comparison */
+
+  if ((result = b->vendor_id - a->vendor_id) == 0)
+    result = b->product_id - a->product_id;
+
+  return (result);
+}
+
+
 /*
  * 'find_device()' - Find or enumerate USB printers.
  */
@@ -657,7 +803,8 @@ find_device(usb_cb_t   cb,          /* I - Callback function */
                                        /* Pointer to current alternate setting */
   const struct libusb_endpoint_descriptor *endpptr = NULL;
                                        /* Pointer to current endpoint */
-  ssize_t               numdevs,        /* number of connected devices */
+  ssize_t               err = 0,       /* Error code */
+                        numdevs,        /* number of connected devices */
                         i = 0;
   uint8_t              conf,           /* Current configuration */
                        iface,          /* Current interface */
@@ -676,7 +823,13 @@ find_device(usb_cb_t   cb,         /* I - Callback function */
   * Initialize libusb...
   */
 
-  libusb_init(NULL);
+  err = libusb_init(NULL);
+  if (err)
+  {
+    fprintf(stderr, "ERROR: Unable to initialize USB access via libusb, libusb error %i (%s)\n", (int)err, libusb_strerror((int)err));
+    return (NULL);
+  }
+
   numdevs = libusb_get_device_list(NULL, &list);
   fprintf(stderr, "DEBUG: libusb_get_device_list=%d\n", (int)numdevs);
 
@@ -694,12 +847,22 @@ find_device(usb_cb_t   cb,                /* I - Callback function */
       * a printer...
       */
 
-      libusb_get_device_descriptor(device, &devdesc);
+      if (libusb_get_device_descriptor(device, &devdesc) < 0)
+       continue;
 
       if (!devdesc.bNumConfigurations || !devdesc.idVendor ||
           !devdesc.idProduct)
        continue;
 
+      printer.quirks = find_quirks(devdesc.idVendor, devdesc.idProduct);
+
+     /*
+      * Ignore blacklisted printers...
+      */
+
+      if (printer.quirks & USB_QUIRK_BLACKLIST)
+        continue;
+
       for (conf = 0; conf < devdesc.bNumConfigurations; conf ++)
       {
        if (libusb_get_config_descriptor(device, conf, &confptr) < 0)
@@ -724,15 +887,20 @@ find_device(usb_cb_t   cb,                /* I - Callback function */
            * 1284.4 (packet mode) protocol as well.
            */
 
-           if (altptr->bInterfaceClass != LIBUSB_CLASS_PRINTER ||
-               altptr->bInterfaceSubClass != 1 ||
+           if (((altptr->bInterfaceClass != LIBUSB_CLASS_PRINTER ||
+                 altptr->bInterfaceSubClass != 1) &&
+                ((printer.quirks & USB_QUIRK_VENDOR_CLASS) == 0)) ||
                (altptr->bInterfaceProtocol != 1 &&     /* Unidirectional */
                 altptr->bInterfaceProtocol != 2) ||    /* Bidirectional */
                altptr->bInterfaceProtocol < protocol)
              continue;
 
-           read_endp  = -1;
-           write_endp = -1;
+           if (printer.quirks & USB_QUIRK_VENDOR_CLASS)
+             fprintf(stderr, "DEBUG: Printer does not report class 7 and/or "
+                     "subclass 1 but works as a printer anyway\n");
+
+           read_endp  = 0xff;
+           write_endp = 0xff;
 
            for (endp = 0, endpptr = altptr->endpoint;
                 endp < altptr->bNumEndpoints;
@@ -746,7 +914,7 @@ find_device(usb_cb_t   cb,          /* I - Callback function */
                  write_endp = endp;
              }
 
-            if (write_endp >= 0)
+            if (write_endp != 0xff)
            {
             /*
              * Save the best match so far...
@@ -755,7 +923,10 @@ find_device(usb_cb_t   cb,         /* I - Callback function */
               protocol           = altptr->bInterfaceProtocol;
              printer.altset     = altset;
              printer.write_endp = write_endp;
-             printer.read_endp  = read_endp;
+             if (protocol > 1)
+               printer.read_endp = read_endp;
+             else
+               printer.read_endp = -1;
            }
          }
 
@@ -773,16 +944,41 @@ find_device(usb_cb_t   cb,                /* I - Callback function */
              make_device_uri(&printer, device_id, device_uri,
                              sizeof(device_uri));
 
+             fprintf(stderr, "DEBUG2: Printer found with device ID: %s "
+                     "Device URI: %s\n",
+                     device_id, device_uri);
+
              if ((*cb)(&printer, device_uri, device_id, data))
              {
-               printer.read_endp  = confptr->interface[printer.iface].
-                                          altsetting[printer.altset].
-                                          endpoint[printer.read_endp].
-                                          bEndpointAddress;
+               fprintf(stderr, "DEBUG: Device protocol: %d\n",
+                       printer.protocol);
+               if (printer.quirks & USB_QUIRK_UNIDIR)
+               {
+                 printer.read_endp = -1;
+                 fprintf(stderr, "DEBUG: Printer reports bi-di support "
+                         "but in reality works only uni-directionally\n");
+               }
+               if (printer.read_endp != -1)
+               {
+                 printer.read_endp = confptr->interface[printer.iface].
+                                           altsetting[printer.altset].
+                                           endpoint[printer.read_endp].
+                                           bEndpointAddress;
+               }
+               else
+                 fprintf(stderr, "DEBUG: Uni-directional USB communication "
+                         "only!\n");
                printer.write_endp = confptr->interface[printer.iface].
                                           altsetting[printer.altset].
                                           endpoint[printer.write_endp].
                                           bEndpointAddress;
+               if (printer.quirks & USB_QUIRK_NO_REATTACH)
+               {
+                 printer.usblp_attached = 0;
+                 fprintf(stderr, "DEBUG: Printer does not like usblp "
+                         "kernel module to be re-attached after job\n");
+               }
+               libusb_free_config_descriptor(confptr);
                return (&printer);
               }
 
@@ -803,13 +999,43 @@ find_device(usb_cb_t   cb,                /* I - Callback function */
   * Clean up ....
   */
 
-  libusb_free_device_list(list, 1);
+  if (numdevs >= 0)
+    libusb_free_device_list(list, 1);
   libusb_exit(NULL);
 
   return (NULL);
 }
 
 
+/*
+ * 'find_quirks()' - Find the quirks for the given printer, if any.
+ *
+ * First looks for an exact match, then looks for the vendor ID wildcard match.
+ */
+
+static unsigned                                /* O - Quirks flags */
+find_quirks(int vendor_id,             /* I - Vendor ID */
+            int product_id)            /* I - Product ID */
+{
+  usb_quirk_t  key,                    /* Search key */
+               *match;                 /* Matching quirk entry */
+
+
+  key.vendor_id  = vendor_id;
+  key.product_id = product_id;
+
+  if ((match = cupsArrayFind(all_quirks, &key)) != NULL)
+    return (match->quirks);
+
+  key.product_id = 0;
+
+  if ((match = cupsArrayFind(all_quirks, &key)) != NULL)
+    return (match->quirks);
+
+  return (USB_QUIRK_WHITELIST);
+}
+
+
 /*
  * 'get_device_id()' - Get the IEEE-1284 device ID for the printer.
  */
@@ -838,8 +1064,7 @@ get_device_id(usb_printer_t *printer,      /* I - Printer */
   * bytes.  The 1284 spec says the length is stored MSB first...
   */
 
-  length = (((unsigned)buffer[0] & 255) << 8) |
-          ((unsigned)buffer[1] & 255);
+  length = (int)((((unsigned)buffer[0] & 255) << 8) | ((unsigned)buffer[1] & 255));
 
  /*
   * Check to see if the length is larger than our buffer or less than 14 bytes
@@ -850,8 +1075,7 @@ get_device_id(usb_printer_t *printer,      /* I - Printer */
   */
 
   if (length > bufsize || length < 14)
-    length = (((unsigned)buffer[1] & 255) << 8) |
-            ((unsigned)buffer[0] & 255);
+    length = (int)((((unsigned)buffer[1] & 255) << 8) | ((unsigned)buffer[0] & 255));
 
   if (length > bufsize)
     length = bufsize;
@@ -873,7 +1097,7 @@ get_device_id(usb_printer_t *printer,      /* I - Printer */
   * nul-terminate.
   */
 
-  memmove(buffer, buffer + 2, length);
+  memmove(buffer, buffer + 2, (size_t)length);
   buffer[length] = '\0';
 
   return (0);
@@ -915,6 +1139,107 @@ list_cb(usb_printer_t *printer,          /* I - Printer */
 }
 
 
+/*
+ * 'load_quirks()' - Load all quirks files in the /usr/share/cups/usb directory.
+ */
+
+static void
+load_quirks(void)
+{
+  const char   *datadir;               /* CUPS_DATADIR environment variable */
+  char         filename[1024],         /* Filename */
+               line[1024];             /* Line from file */
+  cups_dir_t   *dir;                   /* Directory */
+  cups_dentry_t        *dent;                  /* Directory entry */
+  cups_file_t  *fp;                    /* Quirks file */
+  usb_quirk_t  *quirk;                 /* New quirk */
+
+
+  all_quirks = cupsArrayNew((cups_array_func_t)compare_quirks, NULL);
+
+  if ((datadir = getenv("CUPS_DATADIR")) == NULL)
+    datadir = CUPS_DATADIR;
+
+  snprintf(filename, sizeof(filename), "%s/usb", datadir);
+  if ((dir = cupsDirOpen(filename)) == NULL)
+  {
+    perror(filename);
+    return;
+  }
+
+  fprintf(stderr, "DEBUG: Loading USB quirks from \"%s\".\n", filename);
+
+  while ((dent = cupsDirRead(dir)) != NULL)
+  {
+    if (!S_ISREG(dent->fileinfo.st_mode))
+      continue;
+
+    snprintf(filename, sizeof(filename), "%s/usb/%s", datadir, dent->filename);
+    if ((fp = cupsFileOpen(filename, "r")) == NULL)
+    {
+      perror(filename);
+      continue;
+    }
+
+    while (cupsFileGets(fp, line, sizeof(line)))
+    {
+     /*
+      * Skip blank and comment lines...
+      */
+
+      if (line[0] == '#' || !line[0])
+        continue;
+
+     /*
+      * Add a quirk...
+      */
+
+      if ((quirk = calloc(1, sizeof(usb_quirk_t))) == NULL)
+      {
+        perror("DEBUG: Unable to allocate memory for quirk");
+        break;
+      }
+
+      if (sscanf(line, "%x%x", &quirk->vendor_id, &quirk->product_id) < 1)
+      {
+        fprintf(stderr, "DEBUG: Bad line: %s\n", line);
+        free(quirk);
+        continue;
+      }
+
+      if (strstr(line, " blacklist"))
+        quirk->quirks |= USB_QUIRK_BLACKLIST;
+
+      if (strstr(line, " delay-close"))
+        quirk->quirks |= USB_QUIRK_DELAY_CLOSE;
+
+      if (strstr(line, " no-reattach"))
+        quirk->quirks |= USB_QUIRK_NO_REATTACH;
+
+      if (strstr(line, " soft-reset"))
+        quirk->quirks |= USB_QUIRK_SOFT_RESET;
+
+      if (strstr(line, " unidir"))
+        quirk->quirks |= USB_QUIRK_UNIDIR;
+
+      if (strstr(line, " usb-init"))
+        quirk->quirks |= USB_QUIRK_USB_INIT;
+
+      if (strstr(line, " vendor-class"))
+        quirk->quirks |= USB_QUIRK_VENDOR_CLASS;
+
+      cupsArrayAdd(all_quirks, quirk);
+    }
+
+    cupsFileClose(fp);
+  }
+
+  fprintf(stderr, "DEBUG: Loaded %d quirks.\n", cupsArrayCount(all_quirks));
+
+  cupsDirClose(dir);
+}
+
+
 /*
  * 'make_device_uri()' - Create a device URI for a USB printer.
  */
@@ -1086,15 +1411,20 @@ open_device(usb_printer_t *printer,     /* I - Printer */
   * Try opening the printer...
   */
 
-  if (libusb_open(printer->device, &printer->handle) < 0)
+  if ((errcode = libusb_open(printer->device, &printer->handle)) < 0)
+  {
+    fprintf(stderr, "DEBUG: Failed to open device, code: %d\n",
+           errcode);
     return (-1);
+  }
 
   printer->usblp_attached = 0;
+  printer->reset_after_job = 0;
 
   if (verbose)
     fputs("STATE: +connecting-to-device\n", stderr);
 
-  if ((errcode = libusb_get_device_descriptor (printer->device, &devdesc)) < 0)
+  if ((errcode = libusb_get_device_descriptor(printer->device, &devdesc)) < 0)
   {
     fprintf(stderr, "DEBUG: Failed to get device descriptor, code: %d\n",
            errcode);
@@ -1123,9 +1453,14 @@ open_device(usb_printer_t *printer,      /* I - Printer */
   else
   {
     printer->usblp_attached = 0;
-    fprintf(stderr, "DEBUG: Failed to check whether %04x:%04x has the \"usblp\" kernel module attached\n",
-             devdesc.idVendor, devdesc.idProduct);
-    goto error;
+
+    if (errcode != LIBUSB_ERROR_NOT_SUPPORTED)
+    {
+      fprintf(stderr,
+              "DEBUG: Failed to check whether %04x:%04x has the \"usblp\" "
+              "kernel module attached\n", devdesc.idVendor, devdesc.idProduct);
+      goto error;
+    }
   }
 
  /*
@@ -1142,12 +1477,22 @@ open_device(usb_printer_t *printer,     /* I - Printer */
                0, 0, (unsigned char *)&current, 1, 5000) < 0)
     current = 0;                       /* Assume not configured */
 
-  libusb_get_device_descriptor(printer->device, &devdesc);
-  libusb_get_config_descriptor(printer->device, printer->conf, &confptr);
+  printer->origconf = current;
+
+  if ((errcode =
+       libusb_get_config_descriptor (printer->device, printer->conf, &confptr))
+      < 0)
+  {
+    fprintf(stderr, "DEBUG: Failed to get config descriptor for %04x:%04x\n",
+           devdesc.idVendor, devdesc.idProduct);
+    goto error;
+  }
   number1 = confptr->bConfigurationValue;
 
   if (number1 != current)
   {
+    fprintf(stderr, "DEBUG: Switching USB device configuration: %d -> %d\n",
+           current, number1);
     if ((errcode = libusb_set_configuration(printer->handle, number1)) < 0)
     {
      /*
@@ -1162,38 +1507,6 @@ open_device(usb_printer_t *printer,      /* I - Printer */
     }
   }
 
- /*
-  * Get the "usblp" kernel module out of the way. This backend only
-  * works without the module attached.
-  */
-
-  errcode = libusb_kernel_driver_active(printer->handle, printer->iface);
-  if (errcode == 0)
-    printer->usblp_attached = 0;
-  else if (errcode == 1)
-  {
-    printer->usblp_attached = 1;
-    if ((errcode =
-        libusb_detach_kernel_driver(printer->handle, printer->iface)) < 0)
-    {
-      fprintf(stderr, "DEBUG: Failed to detach \"usblp\" module from %04x:%04x\n",
-             devdesc.idVendor, devdesc.idProduct);
-      goto error;
-    }
-  }
-  else
-  {
-    printer->usblp_attached = 0;
-
-    if (errcode != LIBUSB_ERROR_NOT_SUPPORTED)
-    {
-      fprintf(stderr,
-              "DEBUG: Failed to check whether %04x:%04x has the \"usblp\" "
-              "kernel module attached\n", devdesc.idVendor, devdesc.idProduct);
-      goto error;
-    }
-  }
-
  /*
   * Claim interfaces as needed...
   */
@@ -1211,6 +1524,16 @@ open_device(usb_printer_t *printer,      /* I - Printer */
 
       goto error;
     }
+    else if ((errcode = libusb_detach_kernel_driver(printer->handle, printer->iface)) < 0)
+    {
+      fprintf(stderr,
+              "DEBUG: Failed to detach \"usblp\" module from %04x:%04x\n",
+              devdesc.idVendor, devdesc.idProduct);
+
+      goto error;
+    }
+
+    sleep (1);
   }
 
  /*
@@ -1406,7 +1729,7 @@ static void *read_thread(void *reference)
     {
       fprintf(stderr, "DEBUG: Read %d bytes of back-channel data...\n",
               (int)rbytes);
-      cupsBackChannelWrite((const char *)readbuffer, rbytes, 1.0);
+      cupsBackChannelWrite((const char *)readbuffer, (size_t)rbytes, 1.0);
     }
     else if (readstatus == LIBUSB_ERROR_TIMEOUT)
       fputs("DEBUG: Got USB transaction timeout during read.\n", stderr);
@@ -1419,8 +1742,7 @@ static void *read_thread(void *reference)
     * Make sure this loop executes no more than once every 250 miliseconds...
     */
 
-    if ((readstatus != LIBUSB_SUCCESS || rbytes == 0) &&
-        (g.wait_eof || !g.read_thread_stop))
+    if ((g.wait_eof || !g.read_thread_stop))
     {
       gettimeofday(&now, NULL);
       if (timercmp(&now, &end, <))
@@ -1581,13 +1903,15 @@ sidechannel_thread(void *reference)
  * 'soft_reset()' - Send a soft reset to the device.
  */
 
-static void soft_reset(void)
+static void
+soft_reset(void)
 {
   fd_set         input_set;            /* Input set for select() */
   struct timeval  tv;                  /* Time value */
   char           buffer[2048];         /* Buffer */
   struct timespec cond_timeout;                /* pthread condition timeout */
 
+
  /*
   * Send an abort once a second until the I/O lock is released by the main
   * thread...
@@ -1632,7 +1956,7 @@ static void soft_reset(void)
   * Send the reset...
   */
 
-  libusb_reset_device (g.printer->handle);
+  soft_reset_printer(g.printer);
 
  /*
   * Release the I/O lock...
@@ -1646,6 +1970,45 @@ static void soft_reset(void)
 
 
 /*
- * End of "$Id$".
+ * 'soft_reset_printer()' - Do the soft reset request specific to printers
+ *
+ * This soft reset is specific to the printer device class and is much less
+ * invasive than the general USB reset libusb_reset_device(). Especially it
+ * does never happen that the USB addressing and configuration changes. What
+ * is actually done is that all buffers get flushed and the bulk IN and OUT
+ * pipes get reset to their default states. This clears all stall conditions.
+ * See http://cholla.mmto.org/computers/linux/usb/usbprint11.pdf
  */
 
+static int                             /* O - 0 on success, < 0 on error */
+soft_reset_printer(
+    usb_printer_t *printer)            /* I - Printer */
+{
+  struct libusb_config_descriptor *confptr = NULL;
+                                        /* Pointer to current configuration */
+  int interface,                       /* Interface to reset */
+      errcode;                         /* Error code */
+
+
+  if (libusb_get_config_descriptor(printer->device, printer->conf,
+                                   &confptr) < 0)
+    interface = printer->iface;
+  else
+    interface = confptr->interface[printer->iface].
+                         altsetting[printer->altset].bInterfaceNumber;
+
+  libusb_free_config_descriptor(confptr);
+
+  if ((errcode = libusb_control_transfer(printer->handle,
+                                        LIBUSB_REQUEST_TYPE_CLASS |
+                                        LIBUSB_ENDPOINT_OUT |
+                                        LIBUSB_RECIPIENT_OTHER,
+                                        2, 0, interface, NULL, 0, 5000)) < 0)
+    errcode = libusb_control_transfer(printer->handle,
+                                     LIBUSB_REQUEST_TYPE_CLASS |
+                                     LIBUSB_ENDPOINT_OUT |
+                                     LIBUSB_RECIPIENT_INTERFACE,
+                                     2, 0, interface, NULL, 0, 5000);
+
+  return (errcode);
+}