]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - backend/usb-darwin.c
Import CUPS v2.0.3
[thirdparty/cups.git] / backend / usb-darwin.c
index 2ec10d4a156be90d957d1cfc0a203ed60e90894d..cc85f885f2e6b4451632102dbb6cfadec304342e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * "$Id: usb-darwin.c 11669 2014-03-04 14:53:34Z msweet $"
+ * "$Id: usb-darwin.c 12529 2015-02-23 18:57:57Z msweet $"
  *
  * Copyright 2005-2014 Apple Inc. All rights reserved.
  *
 #include <spawn.h>
 #include <pthread.h>
 
+/*
+ * Include necessary headers.
+ */
+
 extern char **environ;
 
 
@@ -134,6 +138,7 @@ struct crashreporter_annotations_t gCRAnnotations
 #define kUSBPrintingProtocolNoOpen             0
 #define kUSBPrintingProtocolUnidirectional     1
 #define kUSBPrintingProtocolBidirectional      2
+#define kUSBPrintingProtocolIPP                        4
 
 typedef IOUSBInterfaceInterface190     **printer_interface_t;
 
@@ -198,7 +203,7 @@ typedef struct classdriver_s                /**** g.classdriver context ****/
 
 } classdriver_t;
 
-typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj);
+typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting);
 
 typedef struct iterator_reference_s    /**** Iterator reference data */
 {
@@ -226,6 +231,7 @@ typedef struct globals_s
   CFStringRef          serial;
   UInt32               location;
   UInt8                        interfaceNum;
+  UInt8                        alternateSetting;
 
   CFRunLoopTimerRef    status_timer;
 
@@ -258,8 +264,9 @@ int Iterating = 0;                  /* Are we iterating the bus? */
  * Local functions...
  */
 
-static Boolean find_device_cb(void *refcon, io_service_t obj);
-static Boolean list_device_cb(void *refcon, io_service_t obj);
+static Boolean find_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting);
+static Boolean list_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting);
+
 static CFStringRef cfstr_create_trim(const char *cstr);
 static CFStringRef copy_value_for_key(CFStringRef deviceID, CFStringRef *keys);
 static kern_return_t load_classdriver(CFStringRef driverPath, printer_interface_t interface, classdriver_t ***printerDriver);
@@ -267,16 +274,13 @@ static kern_return_t load_printerdriver(CFStringRef *driverBundlePath);
 static kern_return_t registry_close(void);
 static kern_return_t registry_open(CFStringRef *driverBundlePath);
 static kern_return_t unload_classdriver(classdriver_t ***classdriver);
-static OSStatus copy_deviceid(classdriver_t **printer, CFStringRef *deviceID);
+
 static void *read_thread(void *reference);
 static void *sidechannel_thread(void *reference);
-static void copy_deviceinfo(CFStringRef deviceIDString, CFStringRef *make, CFStringRef *model, CFStringRef *serial);
-static void copy_devicestring(io_service_t usbInterface, CFStringRef *deviceID, UInt32 *deviceLocation, UInt8 *interfaceNum);
 static void device_added(void *userdata, io_iterator_t iterator);
 static void get_device_id(cups_sc_status_t *status, char *data, int *datalen);
 static void iterate_printers(iterator_callback_t callBack, void *userdata);
 static void parse_options(char *options, char *serial, int serial_size, UInt32 *location, Boolean *wait_eof);
-static void release_deviceinfo(CFStringRef *make, CFStringRef *model, CFStringRef *serial);
 static void setup_cfLanguage(void);
 static void soft_reset(void);
 static void status_timer_cb(CFRunLoopTimerRef timer, void *info);
@@ -296,6 +300,14 @@ static const char *next_line (const char *buffer);
 static void parse_pserror (char *sockBuffer, int len);
 #endif /* PARSE_PS_ERRORS */
 
+static IOUSBInterfaceInterface220 **usb_interface220_for_service(io_service_t usbClass);
+static IOUSBDeviceInterface **usb_device_interface_for_device(io_service_t usbDevice);
+static CFStringRef printer_interface_deviceid(IOUSBInterfaceInterface220 **printer, UInt8 alternateSetting);
+static CFStringRef printer_interface_indexed_description(IOUSBInterfaceInterface220 ** printer, UInt8 index, UInt16 language);
+static CFStringRef deviceIDCopyManufacturer(CFStringRef deviceID);
+static CFStringRef deviceIDCopyModel(CFStringRef deviceID);
+static CFStringRef deviceIDCopySerialNumber(CFStringRef deviceID);
+
 #pragma mark -
 
 /*
@@ -1084,228 +1096,269 @@ sidechannel_thread(void *reference)
  * 'iterate_printers()' - Iterate over all the printers.
  */
 
-static void iterate_printers(iterator_callback_t callBack,
-                            void *userdata)
+static void iterate_printers(iterator_callback_t callBack, void *userdata)
 {
-  Iterating = 1;
-
-  mach_port_t  masterPort = 0x0;
-  kern_return_t kr = IOMasterPort (bootstrap_port, &masterPort);
-
-  if (kr == kIOReturnSuccess && masterPort != 0x0)
-  {
-    io_iterator_t addIterator = 0x0;
-
-    iterator_reference_t reference = { callBack, userdata, true };
-    IONotificationPortRef addNotification = IONotificationPortCreate(masterPort);
-
-    int klass = kUSBPrintingClass;
-    int subklass = kUSBPrintingSubclass;
-
-    CFNumberRef usb_klass = CFNumberCreate(NULL, kCFNumberIntType, &klass);
-    CFNumberRef usb_subklass = CFNumberCreate(NULL, kCFNumberIntType, &subklass);
-    CFMutableDictionaryRef usbPrinterMatchDictionary = IOServiceMatching(kIOUSBInterfaceClassName);
-
-    CFDictionaryAddValue(usbPrinterMatchDictionary, CFSTR("bInterfaceClass"), usb_klass);
-    CFDictionaryAddValue(usbPrinterMatchDictionary, CFSTR("bInterfaceSubClass"), usb_subklass);
-
-    CFRelease(usb_klass);
-    CFRelease(usb_subklass);
-
-    IOServiceAddMatchingNotification(addNotification, kIOMatchedNotification, usbPrinterMatchDictionary, &device_added, &reference, &addIterator);
-    if (addIterator != 0x0)
+    Iterating = 1;
+    
+    mach_port_t        masterPort = 0x0;
+    kern_return_t kr = IOMasterPort (bootstrap_port, &masterPort);
+    
+    if (kr == kIOReturnSuccess && masterPort != 0x0)
     {
-      device_added (&reference, addIterator);
-
-      if (reference.keepRunning)
-      {
-       CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification), kCFRunLoopDefaultMode);
-       CFRunLoopRun();
-      }
-      IOObjectRelease(addIterator);
+        iterator_reference_t reference = { callBack, userdata, true };
+        
+        IONotificationPortRef addNotification = IONotificationPortCreate(masterPort);
+        io_iterator_t addIterator = IO_OBJECT_NULL;
+        
+        kr = IOServiceAddMatchingNotification(addNotification, kIOFirstMatchNotification, IOServiceMatching(kIOUSBDeviceClassName),
+                                              &device_added, &reference, &addIterator);
+        if (kr == kIOReturnSuccess && addIterator != IO_OBJECT_NULL)
+        {
+            device_added(&reference, addIterator);
+            if (reference.keepRunning)
+            {
+                CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification), kCFRunLoopDefaultMode);
+                CFRunLoopRun();
+            }
+            IOObjectRelease(addIterator);
+        }
+        mach_port_deallocate(mach_task_self(), masterPort);
     }
-    mach_port_deallocate(mach_task_self(), masterPort);
-  }
-
-  Iterating = 0;
+    
+    Iterating = 0;
 }
 
 
 /*
  * 'device_added()' - Device added notifier.
  */
+#define IsPrintingInterface(c,s,p) ((c) == kUSBPrintingInterfaceClass && (s) == kUSBPrintingSubclass && (p) != kUSBPrintingProtocolIPP)
 
-static void device_added(void *userdata,
-                        io_iterator_t iterator)
+static void device_added(void *userdata, io_iterator_t iterator)
 {
-  iterator_reference_t *reference = userdata;
-
-  io_service_t obj;
-  while (reference->keepRunning && (obj = IOIteratorNext(iterator)) != 0x0)
-  {
-    if (reference->callback != NULL)
-      reference->keepRunning = reference->callback(reference->userdata, obj);
-
-    IOObjectRelease(obj);
-  }
+    iterator_reference_t *reference = userdata;
+    io_service_t device;
+    
+    while (reference->keepRunning && (device = IOIteratorNext(iterator)) != 0x0)
+    {
+        UInt32 locationID = 0;
+        IOUSBDeviceInterface **devIntf = NULL;
+        io_iterator_t intfIterator = IO_OBJECT_NULL;
+        io_object_t intf = IO_OBJECT_NULL;
+
+        devIntf = usb_device_interface_for_device(device);
+        if (devIntf == NULL)
+            goto device_added_done;
+
+        UInt16 vendorUniqueID;
+        if ((*devIntf)->GetDeviceVendor(devIntf, &vendorUniqueID) != kIOReturnSuccess || vendorUniqueID == kAppleVendorID || vendorUniqueID == 0x0A5C)
+            goto device_added_done;
+
+        if ((*devIntf)->GetLocationID(devIntf, &locationID) != kIOReturnSuccess)
+            goto device_added_done;
+
+        IOUSBFindInterfaceRequest req = { kIOUSBFindInterfaceDontCare, kIOUSBFindInterfaceDontCare, kIOUSBFindInterfaceDontCare, kIOUSBFindInterfaceDontCare };
+        if ((*devIntf)->CreateInterfaceIterator(devIntf, &req, &intfIterator) != kIOReturnSuccess)
+            goto device_added_done;
+
+        while (reference->keepRunning && (intf = IOIteratorNext(intfIterator)))
+        {
+            IOUSBInterfaceInterface220 **intf220 = usb_interface220_for_service(intf);
+            if (intf220 != NULL)
+            {
+                UInt8 intfClass = 0, intfSubclass = 0, intfProtocol = 0, intfNumber = 0;
+
+                (*intf220)->GetInterfaceClass(intf220, &intfClass);
+                (*intf220)->GetInterfaceSubClass(intf220, &intfSubclass);
+                (*intf220)->GetInterfaceProtocol(intf220, &intfProtocol);
+                (*intf220)->GetInterfaceNumber(intf220, &intfNumber);
+
+                if (IsPrintingInterface(intfClass, intfSubclass, intfProtocol))
+                {
+                    CFStringRef deviceIDString = printer_interface_deviceid(intf220, 0);
+                    if (deviceIDString != NULL)
+                    {
+                        reference->keepRunning = reference->callback(userdata, intf, deviceIDString, locationID, intfNumber, 0);
+                        CFRelease(deviceIDString);
+                    }
+                }
+
+                IOUSBInterfaceDescriptor *intfDesc = nil;
+                while (reference->keepRunning && (intfDesc = (IOUSBInterfaceDescriptor *)(*intf220)->FindNextAssociatedDescriptor(intf220, intfDesc, kUSBInterfaceDesc)))
+                {
+                    intfClass = intfDesc->bInterfaceClass;
+                    intfSubclass = intfDesc->bInterfaceSubClass;
+                    intfProtocol = intfDesc->bInterfaceProtocol;
+
+                    if ((IsPrintingInterface(intfClass, intfSubclass, intfProtocol)))
+                    {
+                        CFStringRef deviceIDString = printer_interface_deviceid(intf220, intfDesc->bAlternateSetting);
+                        if (deviceIDString != NULL)
+                        {
+                            reference->keepRunning = reference->callback(userdata, intf, deviceIDString, locationID, intfNumber, intfDesc->bAlternateSetting);
+                            CFRelease(deviceIDString);
+                        }
+                    }
+                }
+                (*intf220)->Release(intf220);
+            }
+        }
 
-  /* One last call to the call back now that we are not longer have printers left to iterate...
-   */
-  if (reference->keepRunning && reference->callback)
-    reference->keepRunning = reference->callback(reference->userdata, 0x0);
+        device_added_done:
+            if (devIntf != NULL) (*devIntf)->Release(devIntf);
+            if (intfIterator != IO_OBJECT_NULL) IOObjectRelease(intfIterator);
 
-  if (!reference->keepRunning)
-    CFRunLoopStop(CFRunLoopGetCurrent());
+        IOObjectRelease(device);
+    }
+    
+    /* One last call to the call back now that we are not longer have printers left to iterate...
+     */
+    if (reference->keepRunning && reference->callback)
+        reference->keepRunning = reference->callback(reference->userdata, IO_OBJECT_NULL, NULL, 0, 0, 0);
+    
+    if (!reference->keepRunning)
+        CFRunLoopStop(CFRunLoopGetCurrent());
 }
 
-
 /*
  * 'list_device_cb()' - list_device iterator callback.
  */
 
-static Boolean list_device_cb(void *refcon,
-                             io_service_t obj)
+static Boolean list_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting)
 {
-  Boolean keepRunning = (obj != 0x0);
-
-
-  (void)refcon;
+    (void)interfaceNum;
+    (void)alternateSetting;
 
-  if (keepRunning)
-  {
-    CFStringRef deviceIDString = NULL;
-    UInt32 deviceLocation = 0;
-    UInt8      interfaceNum = 0;
-
-    copy_devicestring(obj, &deviceIDString, &deviceLocation, &interfaceNum);
-    if (deviceIDString != NULL)
+    if (obj != IO_OBJECT_NULL)
     {
-      CFStringRef make = NULL,  model = NULL, serial = NULL;
-      char uristr[1024], makestr[1024], modelstr[1024], serialstr[1024];
-      char optionsstr[1024], idstr[1024], make_modelstr[1024];
-
-      copy_deviceinfo(deviceIDString, &make, &model, &serial);
-      CFStringGetCString(deviceIDString, idstr, sizeof(idstr),
-                         kCFStringEncodingUTF8);
-      backendGetMakeModel(idstr, make_modelstr, sizeof(make_modelstr));
-
-      modelstr[0] = '/';
-
-      if (!make ||
-          !CFStringGetCString(make, makestr, sizeof(makestr),
-                             kCFStringEncodingUTF8))
-        strlcpy(makestr, "Unknown", sizeof(makestr));
-
-      if (!model ||
-          !CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1,
-                             kCFStringEncodingUTF8))
-        strlcpy(modelstr + 1, "Printer", sizeof(modelstr) - 1);
-
-      optionsstr[0] = '\0';
-      if (serial != NULL)
-      {
-        CFStringGetCString(serial, serialstr, sizeof(serialstr), kCFStringEncodingUTF8);
-       snprintf(optionsstr, sizeof(optionsstr), "?serial=%s", serialstr);
-      }
-      else if (deviceLocation != 0)
-       snprintf(optionsstr, sizeof(optionsstr), "?location=%x", (unsigned)deviceLocation);
-
-      httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr);
-      strlcat(uristr, optionsstr, sizeof(uristr));
-
-      cupsBackendReport("direct", uristr, make_modelstr, make_modelstr, idstr,
-                        NULL);
-
-      release_deviceinfo(&make, &model, &serial);
-      CFRelease(deviceIDString);
+        CFStringRef make = NULL;
+        CFStringRef model = NULL;
+        CFStringRef serial = NULL;
+        
+        char uristr[1024], makestr[1024], modelstr[1024], serialstr[1024];
+        char optionsstr[1024], idstr[1024], make_modelstr[1024];
+        
+        CFStringGetCString(deviceIDString, idstr, sizeof(idstr), kCFStringEncodingUTF8);
+        backendGetMakeModel(idstr, make_modelstr, sizeof(make_modelstr));
+        
+        modelstr[0] = '/';
+        
+        if (make  == NULL || !CFStringGetCString(make, makestr, sizeof(makestr), kCFStringEncodingUTF8))
+            strlcpy(makestr, "Unknown", sizeof(makestr));
+        
+        if (model == NULL || !CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1, kCFStringEncodingUTF8))
+            strlcpy(modelstr + 1, "Printer", sizeof(modelstr) - 1);
+        
+        optionsstr[0] = '\0';
+        if (serial != NULL && CFStringGetCString(serial, serialstr, sizeof(serialstr), kCFStringEncodingUTF8))
+            snprintf(optionsstr, sizeof(optionsstr), "?serial=%s", serialstr);
+        else if (deviceLocation != 0)
+            snprintf(optionsstr, sizeof(optionsstr), "?location=%x", (unsigned)deviceLocation);
+        
+        httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr);
+        strlcat(uristr, optionsstr, sizeof(uristr));
+        
+        cupsBackendReport("direct", uristr, make_modelstr, make_modelstr, idstr,
+                          NULL);
     }
-  }
-
-  return keepRunning;
+    
+    return obj != IO_OBJECT_NULL;
 }
 
-
 /*
  * 'find_device_cb()' - print_device iterator callback.
  */
-
-static Boolean find_device_cb(void *refcon,
-                             io_service_t obj)
+static Boolean find_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting)
 {
-  Boolean keepLooking = true;
-
-  if (obj != 0x0)
-  {
-    CFStringRef idString = NULL;
-    UInt32 location = ~0U;
-    UInt8      interfaceNum = 0;
-
-    copy_devicestring(obj, &idString, &location, &interfaceNum);
-    if (idString != NULL)
+    Boolean keepLooking = true;
+    
+    if (obj != IO_OBJECT_NULL)
     {
-      CFStringRef make = NULL,  model = NULL, serial = NULL;
-
-      copy_deviceinfo(idString, &make, &model, &serial);
-      if (make && CFStringCompare(make, g.make, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
-      {
-       if (model && CFStringCompare(model, g.model, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
-       {
-         if (g.serial != NULL && CFStringGetLength(g.serial) > 0)
-         {
-           if (serial != NULL && CFStringCompare(serial, g.serial, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
-           {
-             IOObjectRetain(obj);
-             g.printer_obj = obj;
-             keepLooking = false;
-           }
-         }
-         else
-         {
-           if (g.printer_obj != 0)
-             IOObjectRelease(g.printer_obj);
-
-           g.printer_obj = obj;
-           IOObjectRetain(obj);
-
-           if (g.location == 0 || g.location == location)
-             keepLooking = false;
-         }
-         if ( !keepLooking )
-               g.interfaceNum = interfaceNum;
-       }
-      }
-
-      release_deviceinfo(&make, &model, &serial);
-      CFRelease(idString);
+        CFStringRef make = deviceIDCopyManufacturer(deviceIDString);
+        CFStringRef model = deviceIDCopyModel(deviceIDString);
+        CFStringRef serial = deviceIDCopySerialNumber(deviceIDString);
+        
+        if (make && CFStringCompare(make, g.make, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
+        {
+            if (model && CFStringCompare(model, g.model, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
+            {
+                if (g.serial != NULL && CFStringGetLength(g.serial) > 0)
+                {
+                    if (serial != NULL && CFStringCompare(serial, g.serial, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
+                    {
+                        IOObjectRetain(obj);
+                        g.printer_obj = obj;
+                        g.alternateSetting = alternateSetting;
+                        keepLooking = false;
+                    }
+                }
+                else
+                {
+                    if (g.printer_obj != 0)
+                        IOObjectRelease(g.printer_obj);
+                    
+                    g.alternateSetting = alternateSetting;
+                    g.printer_obj = obj;
+                    IOObjectRetain(obj);
+                    
+                    if (g.location == 0 || g.location == deviceLocation)
+                        keepLooking = false;
+                }
+                
+                if ( !keepLooking )
+                    g.interfaceNum = interfaceNum;
+            }
+        }
+        
+        if (make) CFRelease(make);
+        if (model) CFRelease(model);
+        if (serial) CFRelease(serial);
     }
-  }
-  else
-  {
-    keepLooking = (g.printer_obj == 0);
-    if (obj == 0x0 && keepLooking)
+    else
     {
-      CFRunLoopTimerContext context = { 0, refcon, NULL, NULL, NULL };
-      CFRunLoopTimerRef timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb, &context);
-      if (timer != NULL)
-      {
-       CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
-       g.status_timer = timer;
-      }
+        keepLooking = (g.printer_obj == 0);
+        if (obj == IO_OBJECT_NULL && keepLooking)
+        {
+            CFRunLoopTimerContext context = { 0, refcon, NULL, NULL, NULL };
+            CFRunLoopTimerRef timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb, &context);
+            if (timer != NULL)
+            {
+                CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
+                g.status_timer = timer;
+            }
+        }
     }
-  }
+    
+    if (!keepLooking && g.status_timer != NULL)
+    {
+        fputs("STATE: -offline-report\n", stderr);
+        _cupsLangPrintFilter(stderr, "INFO", _("The printer is now online."));
+        CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g.status_timer, kCFRunLoopDefaultMode);
+        CFRelease(g.status_timer);
+        g.status_timer = NULL;
+    }
+    
+    return keepLooking;
+}
 
-  if (!keepLooking && g.status_timer != NULL)
-  {
-    fputs("STATE: -offline-report\n", stderr);
-    _cupsLangPrintFilter(stderr, "INFO", _("The printer is now online."));
-    CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g.status_timer, kCFRunLoopDefaultMode);
-    CFRelease(g.status_timer);
-    g.status_timer = NULL;
-  }
+static CFStringRef deviceIDCopySerialNumber(CFStringRef deviceID)
+{
+    CFStringRef serialKeys[] = { CFSTR("SN:"),  CFSTR("SERN:"), NULL };
+    
+    return copy_value_for_key(deviceID, serialKeys);
+}
 
-  return keepLooking;
+static CFStringRef deviceIDCopyModel(CFStringRef deviceID)
+{
+    CFStringRef modelKeys[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL };
+    return copy_value_for_key(deviceID, modelKeys);
 }
 
+static CFStringRef deviceIDCopyManufacturer(CFStringRef deviceID)
+{
+    CFStringRef makeKeys[]   = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL };
+    return copy_value_for_key(deviceID, makeKeys);
+}
 
 /*
  * 'status_timer_cb()' - Status timer callback.
@@ -1338,59 +1391,6 @@ static void status_timer_cb(CFRunLoopTimerRef timer,
 }
 
 
-#pragma mark -
-/*
- * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
- */
-
-static void copy_deviceinfo(CFStringRef deviceIDString,
-                           CFStringRef *make,
-                           CFStringRef *model,
-                           CFStringRef *serial)
-{
-  CFStringRef modelKeys[]  = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL };
-  CFStringRef makeKeys[]   = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL };
-  CFStringRef serialKeys[] = { CFSTR("SN:"),  CFSTR("SERN:"), NULL };
-
-  if (make != NULL)
-    *make = copy_value_for_key(deviceIDString, makeKeys);
-
-  if (model != NULL)
-    *model = copy_value_for_key(deviceIDString, modelKeys);
-
-  if (serial != NULL)
-    *serial = copy_value_for_key(deviceIDString, serialKeys);
-}
-
-
-/*
- * 'release_deviceinfo()' - Release deviceinfo strings.
- */
-
-static void release_deviceinfo(CFStringRef *make,
-                              CFStringRef *model,
-                              CFStringRef *serial)
-{
-  if (make != NULL && *make != NULL)
-  {
-    CFRelease(*make);
-    *make = NULL;
-  }
-
-  if (model != NULL && *model != NULL)
-  {
-    CFRelease(*model);
-    *model = NULL;
-  }
-
-  if (serial != NULL && *serial != NULL)
-  {
-    CFRelease(*serial);
-    *serial = NULL;
-  }
-}
-
-
 #pragma mark -
 /*
  * 'load_classdriver()' - Load a classdriver.
@@ -1522,6 +1522,291 @@ static kern_return_t load_printerdriver(CFStringRef *driverBundlePath)
   return kr;
 }
 
+static IOUSBInterfaceInterface220 **usb_interface220_for_service(io_service_t usbClass)
+{
+       IOUSBInterfaceInterface220 ** intf = NULL;
+       IOCFPlugInInterface **plugin = NULL;
+       SInt32  score;
+       int kr = IOCreatePlugInInterfaceForService(usbClass, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score);
+       if (kr == kIOReturnSuccess)
+       {
+               (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID220), (LPVOID *)&intf);
+               IODestroyPlugInInterface(plugin);
+       }
+
+       return intf;
+}
+
+static IOUSBDeviceInterface **usb_device_interface_for_device(io_service_t usbDevice)
+{
+       IOUSBDeviceInterface ** intf = NULL;
+       IOCFPlugInInterface **plugin = NULL;
+       SInt32  score;
+
+       int kr = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score);
+       if (kr == kIOReturnSuccess)
+       {
+               (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID *)&intf);
+               IODestroyPlugInInterface(plugin);
+       }
+
+       return intf;
+}
+
+
+static CFStringRef printer_interface_deviceid(IOUSBInterfaceInterface220 **printer, UInt8 alternateSetting)
+{
+       // I have tried to make this function as neat as I can, but the possibility of needing to resend
+       // a request to get the entire string makes it hideous...
+       //
+       // We package the job of sending a request up into the block (^sendRequest), which takes the size
+       // it should allocate for the message buffer. It frees the current buffer if one is set and
+       // allocates one of the specified size, then performs the request. We can then easily retry by
+       // calling the block again if we fail to get the whole string the first time around.
+
+       #define kUSBPrintClassGetDeviceID           0
+       #define kDefaultNoDataTimeout               5000L
+       #define pack_device_id_wIndex(intf, alt)  ((UInt16)((((UInt16)(intf)) << 8) | ((UInt8)(alt))))
+
+       if (printer == nil)
+                       return nil;
+
+
+       IOReturn err        = kIOReturnError;
+       UInt8    configurationIndex     = 0;
+       UInt8    interfaceNumber        = 0;
+       size_t   bufferLength           = 256;
+       CFStringRef ret             = NULL;
+
+       if ((*printer)->GetConfigurationValue( printer, &configurationIndex) == kIOReturnSuccess &&
+                       (*printer)->GetInterfaceNumber( printer, &interfaceNumber) == kIOReturnSuccess)
+       {
+               __block IOUSBDevRequestTO       request;
+               IOReturn (^sendRequest)(size_t) = ^ (size_t size)
+               {
+                       if (request.pData)
+                       {
+                               free(request.pData);
+                               request.wLength = 0;
+                               request.pData = NULL;
+                       }
+
+                       IOReturn err = kIOReturnError;
+                       char *buffer = malloc(size);
+                       if (buffer == NULL)
+                               return kIOReturnNoMemory;
+
+                       request.wLength = HostToUSBWord(size);
+                       request.pData = buffer;
+                       err = (*printer)->ControlRequestTO(printer, (UInt8)0, &request);
+                       return err;
+               };
+
+               /* This request takes the 0 based configuration index. IOKit returns a 1 based configuration index */
+               configurationIndex -= 1;
+
+               bzero(&request, sizeof(request));
+
+               request.bmRequestType           = USBmakebmRequestType(kUSBIn, kUSBClass, kUSBInterface);
+               request.bRequest                        = kUSBPrintClassGetDeviceID;
+               request.wValue                          = HostToUSBWord(configurationIndex);
+               request.wIndex                          = HostToUSBWord(pack_device_id_wIndex(interfaceNumber, alternateSetting));
+               request.noDataTimeout           = kDefaultNoDataTimeout;
+               request.completionTimeout       = 0; // Copying behavior from Generic Class Driver
+
+               err = sendRequest(bufferLength);
+
+               if (err == kIOReturnSuccess && request.wLenDone > 1)
+               {
+                       UInt16 actualLength = OSSwapBigToHostInt16(*((UInt16 *)request.pData));
+
+                       if (actualLength > 2 && actualLength <= bufferLength - 2)
+                       {
+                               ret = CFStringCreateWithBytes(NULL, (const UInt8 *) &request.pData[2], actualLength - 2, kCFStringEncodingUTF8, false);
+                       }
+                       else {
+                               err = sendRequest(actualLength);
+                               if (err == kIOReturnSuccess && request.wLenDone > 0)
+                               {
+                                       actualLength = OSSwapBigToHostInt16(*((UInt16 *)request.pData));
+                                       ret = CFStringCreateWithBytes(NULL, (const UInt8 *) &request.pData[2], actualLength - 2, kCFStringEncodingUTF8, false);
+                               }
+                       }
+               }
+
+               if (request.pData)
+                       free(request.pData);
+       }
+
+       CFStringRef manufacturer = deviceIDCopyManufacturer(ret);
+       CFStringRef model = deviceIDCopyManufacturer(ret);
+       CFStringRef serial = deviceIDCopySerialNumber(ret);
+
+       if (manufacturer == NULL || serial == NULL || model == NULL)
+       {
+               IOUSBDevRequestTO               request;
+               IOUSBDeviceDescriptor   desc;
+
+               bzero(&request, sizeof(request));
+
+               request.bmRequestType = USBmakebmRequestType( kUSBIn,  kUSBStandard, kUSBDevice );
+               request.bRequest = kUSBRqGetDescriptor;
+               request.wValue = kUSBDeviceDesc << 8;
+               request.wIndex = 0;
+               request.wLength = sizeof(desc);
+               request.pData = &desc;
+               request.completionTimeout = 0;
+               request.noDataTimeout = 60L;
+
+               err = (*printer)->ControlRequestTO(printer, 0, &request);
+               if (err == kIOReturnSuccess)
+               {
+                       CFMutableStringRef extras = CFStringCreateMutable(NULL, 0);
+                       if (manufacturer == NULL)
+                       {
+                               manufacturer = printer_interface_indexed_description(printer, desc.iManufacturer, kUSBLanguageEnglish);
+                               if (CFStringGetLength(manufacturer) > 0)
+                                       CFStringAppendFormat(extras, NULL, CFSTR("MFG:%@;"), manufacturer);
+                       }
+
+                       if (model == NULL)
+                       {
+                               model = printer_interface_indexed_description(printer, desc.iProduct, kUSBLanguageEnglish);
+                               if (CFStringGetLength(model) > 0)
+                                       CFStringAppendFormat(extras, NULL, CFSTR("MDL:%@;"), manufacturer);
+                       }
+
+                       if (serial == NULL && desc.iSerialNumber != 0)
+                       {
+                               serial = printer_interface_indexed_description(printer, desc.iSerialNumber, kUSBLanguageEnglish);
+                               if (CFStringGetLength(serial) > 0)
+                                       CFStringAppendFormat(extras, NULL, CFSTR("SERN:%@;"), serial);
+                       }
+
+                       if (ret != NULL)
+                       {
+                               CFStringAppend(extras, ret);
+                               CFRelease(ret);
+
+                               ret = extras;
+                       }
+                       else
+                       {
+                               ret = extras;
+                       }
+               }
+       }
+
+       if (manufacturer != NULL)
+               CFRelease(manufacturer);
+       if (model != NULL)
+               CFRelease(model);
+       if (serial != NULL)
+               CFRelease(serial);
+
+
+       /* Remove special characters from the serial number */
+       CFRange range = (serial != NULL ? CFStringFind(serial, CFSTR("+"), 0) : CFRangeMake(0, 0));
+       if (range.length == 1)
+       {
+               range = CFStringFind(ret, serial, 0);
+
+               CFMutableStringRef deviceIDString = CFStringCreateMutableCopy(NULL, 0, ret);
+               CFRelease(ret);
+
+               ret = deviceIDString;
+               CFStringFindAndReplace(deviceIDString, CFSTR("+"), CFSTR(""), range, 0);
+       }
+
+       return (CFStringGetLength(ret) > 0 ? ret : nil);
+}
+
+static CFStringRef printer_interface_indexed_description(IOUSBInterfaceInterface220 ** printer, UInt8 index, UInt16 language)
+{
+       IOReturn err;
+       UInt8 description[256]; // Max possible descriptor length
+       IOUSBDevRequestTO       request;
+
+       bzero(description, 2);
+
+       request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
+       request.bRequest = kUSBRqGetDescriptor;
+       request.wValue = (kUSBStringDesc << 8) | index;
+       request.wIndex = language;
+       request.wLength = 2;
+       request.pData = &description;
+       request.completionTimeout = 0;
+       request.noDataTimeout = 60L;
+
+       err = (*printer)->ControlRequestTO(printer, 0, &request);
+       if (err != kIOReturnSuccess && err != kIOReturnOverrun)
+       {
+               bzero(description, request.wLength);
+
+               // Let's try again full length. Here's why:
+               //      On USB 2.0 controllers, we will not get an overrun error.  We just get a "babble" error
+               //      and no valid data.  So, if we ask for the max size, we will either get it, or we'll get an underrun.
+               //      It looks like we get it w/out an underrun
+
+               request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
+               request.bRequest = kUSBRqGetDescriptor;
+               request.wValue = (kUSBStringDesc << 8) | index;
+               request.wIndex = language;
+               request.wLength = sizeof description;
+               request.pData = &description;
+               request.completionTimeout = 0;
+               request.noDataTimeout = 60L;
+
+               err = (*printer)->ControlRequestTO(printer, 0, &request);
+               if (err != kIOReturnSuccess && err != kIOReturnUnderrun)
+                       return nil;
+       }
+
+       unsigned int length = description[0];
+       if (length == 0)
+               return CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8);
+
+       if (description[1] != kUSBStringDesc)
+               return NULL;
+
+       request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
+       request.bRequest = kUSBRqGetDescriptor;
+       request.wValue = (kUSBStringDesc << 8) | index;
+       request.wIndex = language;
+
+       bzero(description, length);
+       request.wLength = length;
+       request.pData = &description;
+       request.completionTimeout = 0;
+       request.noDataTimeout = 60L;
+
+       err = (*printer)->ControlRequestTO(printer, 0, &request);
+       if (err != kIOReturnSuccess)
+               return nil;
+
+       if (description[1] != kUSBStringDesc)
+               return nil;
+
+       if ((description[0] & 1) != 0)
+               description[0] &= 0xfe;
+
+       char buffer[258] = {};
+       unsigned int maxLength = sizeof buffer;
+       if (description[0] > 1)
+       {
+               length = (description[0]-2)/2;
+
+               if (length > maxLength - 1)
+                       length = maxLength -1;
+
+               for (int i = 0; i < length; i++)
+                       buffer[i] = (char) description[2*i+2];
+
+               buffer[length] = 0;
+       }
+
+       return CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
+}
 
 /*
  * 'registry_open()' - Open a connection to the printer.
@@ -1575,158 +1860,6 @@ static kern_return_t registry_close(void)
   return kIOReturnSuccess;
 }
 
-
-/*
- * 'copy_deviceid()' - Copy the 1284 device id string.
- */
-
-static OSStatus copy_deviceid(classdriver_t **classdriver,
-                             CFStringRef *deviceID)
-{
-  CFStringRef devID = NULL;
-  CFStringRef deviceMake = NULL;
-  CFStringRef deviceModel = NULL;
-  CFStringRef deviceSerial = NULL;
-
-  *deviceID = NULL;
-
-  OSStatus err = (*classdriver)->GetDeviceID(classdriver, &devID, DEFAULT_TIMEOUT);
-
-  copy_deviceinfo(devID, &deviceMake, &deviceModel, &deviceSerial);
-
-  if (deviceMake == NULL || deviceModel == NULL || deviceSerial == NULL)
-  {
-    IOUSBDeviceDescriptor      desc;
-    iodevice_request_t         request;
-
-    request.requestType = USBmakebmRequestType(kUSBIn,  kUSBStandard, kUSBDevice);
-    request.request = kUSBRqGetDescriptor;
-    request.value = (kUSBDeviceDesc << 8) | 0;
-    request.index = 0;
-    request.length = sizeof(desc);
-    request.buffer = &desc;
-    err = (*classdriver)->DeviceRequest(classdriver, &request, DEFAULT_TIMEOUT);
-    if (err == kIOReturnSuccess)
-    {
-      CFMutableStringRef newDevID = CFStringCreateMutable(NULL, 0);
-
-      if (deviceMake == NULL)
-      {
-       CFStringRef data = NULL;
-       err = (*classdriver)->GetString(classdriver, desc.iManufacturer, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
-       if (data != NULL)
-       {
-         CFStringAppendFormat(newDevID, NULL, CFSTR("MFG:%@;"), data);
-         CFRelease(data);
-       }
-      }
-
-      if (deviceModel == NULL)
-      {
-       CFStringRef data = NULL;
-       err = (*classdriver)->GetString(classdriver, desc.iProduct, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
-       if (data != NULL)
-       {
-         CFStringAppendFormat(newDevID, NULL, CFSTR("MDL:%@;"), data);
-         CFRelease(data);
-       }
-      }
-
-      if (deviceSerial == NULL && desc.iSerialNumber != 0)
-      {
-       err = (*classdriver)->GetString(classdriver, desc.iSerialNumber, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &deviceSerial);
-       if (deviceSerial != NULL)
-       {
-         CFStringAppendFormat(newDevID, NULL, CFSTR("SERN:%@;"), deviceSerial);
-       }
-      }
-
-      if (devID != NULL)
-      {
-       CFStringAppend(newDevID, devID);
-       CFRelease(devID);
-      }
-
-      *deviceID = newDevID;
-    }
-  }
-  else
-  {
-    *deviceID = devID;
-  }
-
-  if (*deviceID == NULL)
-      return err;
-
-  /* Remove special characters from the serial number */
-  CFRange range = (deviceSerial != NULL ? CFStringFind(deviceSerial, CFSTR("+"), 0) : CFRangeMake(0, 0));
-  if (range.length == 1) {
-      range = CFStringFind(*deviceID, deviceSerial, 0);
-
-      CFMutableStringRef deviceIDString = CFStringCreateMutableCopy(NULL, 0, *deviceID);
-      CFStringFindAndReplace(deviceIDString, CFSTR("+"), CFSTR(""), range, 0);
-      CFRelease(*deviceID);
-      *deviceID = deviceIDString;
-  }
-
-  release_deviceinfo(&deviceMake, &deviceModel, &deviceSerial);
-
-  return err;
-}
-
-
-/*
- * 'copy_devicestring()' - Copy the 1284 device id string.
- */
-
-static void copy_devicestring(io_service_t usbInterface,
-                             CFStringRef *deviceID,
-                             UInt32 *deviceLocation,
-                             UInt8     *interfaceNumber )
-{
-  IOCFPlugInInterface  **iodev = NULL;
-  SInt32               score;
-  kern_return_t                kr;
-  printer_interface_t  interface;
-  HRESULT              res;
-  classdriver_t        **klassDriver = NULL;
-  CFStringRef          driverBundlePath;
-
-  if ((kr = IOCreatePlugInInterfaceForService(usbInterface,
-                                        kIOUSBInterfaceUserClientTypeID,
-                                        kIOCFPlugInInterfaceID,
-                                        &iodev, &score)) == kIOReturnSuccess)
-  {
-    if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *)
-                                       &interface)) == noErr)
-    {
-      (*interface)->GetLocationID(interface, deviceLocation);
-      (*interface)->GetInterfaceNumber(interface, interfaceNumber);
-
-      driverBundlePath = IORegistryEntryCreateCFProperty(usbInterface,
-                                                        kUSBClassDriverProperty,
-                                                        NULL, kNilOptions);
-
-      kr = load_classdriver(driverBundlePath, interface, &klassDriver);
-
-      if (kr != kIOReturnSuccess && driverBundlePath != NULL)
-       kr = load_classdriver(NULL, interface, &klassDriver);
-
-      if (kr == kIOReturnSuccess && klassDriver != NULL)
-         copy_deviceid(klassDriver, deviceID);
-
-      unload_classdriver(&klassDriver);
-
-      if (driverBundlePath != NULL)
-       CFRelease(driverBundlePath);
-
-      /* (*interface)->Release(interface); */
-    }
-    IODestroyPlugInInterface(iodev);
-  }
-}
-
-
 #pragma mark -
 /*
  * 'copy_value_for_key()' - Copy value string associated with a key.
@@ -2308,15 +2441,31 @@ static void get_device_id(cups_sc_status_t *status,
 {
   CFStringRef deviceIDString = NULL;
 
-  /* GetDeviceID */
-  copy_deviceid(g.classdriver, &deviceIDString);
+  if (g.printer_obj != IO_OBJECT_NULL)
+  {
+    IOUSBInterfaceInterface220 **intf220 = usb_interface220_for_service(g.printer_obj);
+    if (intf220)
+    {
+      deviceIDString = printer_interface_deviceid(intf220, g.alternateSetting);
+      (*intf220)->Release(intf220);
+    }
+  }
+
 
   if (deviceIDString)
   {
-    CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8);
-    *datalen = (int)strlen(data);
+    if (CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8))
+      *datalen = (int)strlen(data);
+    else
+      *datalen = 0;
+    
     CFRelease(deviceIDString);
   }
+  else
+  {
+    *datalen = 0;
+  }
+
   *status  = CUPS_SC_STATUS_OK;
 }
 
@@ -2348,5 +2497,5 @@ log_usb_class_driver(int is_64bit)        /* I - Is the USB class driver 64-bit? */
 
 
 /*
- * End of "$Id: usb-darwin.c 11669 2014-03-04 14:53:34Z msweet $".
+ * End of "$Id: usb-darwin.c 12529 2015-02-23 18:57:57Z msweet $".
  */