chiark / gitweb /
usb_id: add ID_VENDOR_ID, ID_MODEL_ID, ID_USB_INTERFACE_NUM, ID_USB_DRIVER
[elogind.git] / extras / usb_id / usb_id.c
1 /*
2  * usb_id - identify an USB device
3  *
4  * Copyright (c) 2005 SUSE Linux Products GmbH, Germany
5  *
6  * Author:
7  *      Hannes Reinecke <hare@suse.de>
8  *
9  *      This program is free software; you can redistribute it and/or modify it
10  *      under the terms of the GNU General Public License as published by the
11  *      Free Software Foundation version 2 of the License.
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdarg.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include <ctype.h>
20 #include <fcntl.h>
21 #include <errno.h>
22 #include <getopt.h>
23
24 #include "../../udev/udev.h"
25
26 int debug;
27
28 static void log_fn(struct udev *udev, int priority,
29                    const char *file, int line, const char *fn,
30                    const char *format, va_list args)
31 {
32         if (debug) {
33                 fprintf(stderr, "%s: ", fn != NULL ? fn : file);
34                 vfprintf(stderr, format, args);
35         } else {
36                 vsyslog(priority, format, args);
37         }
38 }
39
40 static char vendor_str[64];
41 static char vendor_str_enc[256];
42 static const char *vendor_id = "";
43 static char model_str[64];
44 static char model_str_enc[256];
45 static const char *product_id = "";
46 static char serial_str[UTIL_NAME_SIZE];
47 static char packed_if_str[UTIL_NAME_SIZE];
48 static char revision_str[64];
49 static char type_str[64];
50 static char instance_str[64];
51 static const char *ifnum;
52 static const char *driver;
53
54 static int use_usb_info;
55 static int use_num_info;
56
57 static void set_usb_iftype(char *to, int if_class_num, size_t len)
58 {
59         char *type = "generic";
60
61         switch (if_class_num) {
62         case 1:
63                 type = "audio";
64                 break;
65         case 2: /* CDC-Control */
66                 break;
67         case 3:
68                 type = "hid";
69                 break;
70         case 5: /* Physical */
71                 break;
72         case 6:
73                 type = "media";
74                 break;
75         case 7:
76                 type = "printer";
77                 break;
78         case 8:
79                 type = "storage";
80                 break;
81         case 9:
82                 type = "hub";
83                 break;
84         case 0x0a: /* CDC-Data */
85                 break;
86         case 0x0b: /* Chip/Smart Card */
87                 break;
88         case 0x0d: /* Content Security */
89                 break;
90         case 0x0e:
91                 type = "video";
92                 break;
93         case 0xdc: /* Diagnostic Device */
94                 break;
95         case 0xe0: /* Wireless Controller */
96                 break;
97         case 0xfe: /* Application-specific */
98                 break;
99         case 0xff: /* Vendor-specific */
100                 break;
101         default:
102                 break;
103         }
104         strncpy(to, type, len);
105         to[len-1] = '\0';
106 }
107
108 static int set_usb_mass_storage_ifsubtype(char *to, const char *from, size_t len)
109 {
110         int type_num = 0;
111         char *eptr;
112         char *type = "generic";
113
114         type_num = strtoul(from, &eptr, 0);
115         if (eptr != from) {
116                 switch (type_num) {
117                 case 2:
118                         type = "atapi";
119                         break;
120                 case 3:
121                         type = "tape";
122                         break;
123                 case 4: /* UFI */
124                 case 5: /* SFF-8070i */
125                         type = "floppy";
126                         break;
127                 case 1: /* RBC devices */
128                         type = "rbc";
129                         break;
130                 case 6: /* Transparent SPC-2 devices */
131                         type = "scsi";
132                         break;
133                 default:
134                         break;
135                 }
136         }
137         util_strlcpy(to, type, len);
138         return type_num;
139 }
140
141 static void set_scsi_type(char *to, const char *from, size_t len)
142 {
143         int type_num;
144         char *eptr;
145         char *type = "generic";
146
147         type_num = strtoul(from, &eptr, 0);
148         if (eptr != from) {
149                 switch (type_num) {
150                 case 0:
151                 case 0xe:
152                         type = "disk";
153                         break;
154                 case 1:
155                         type = "tape";
156                         break;
157                 case 4:
158                 case 7:
159                 case 0xf:
160                         type = "optical";
161                         break;
162                 case 5:
163                         type = "cd";
164                         break;
165                 default:
166                         break;
167                 }
168         }
169         util_strlcpy(to, type, len);
170 }
171
172 #define USB_DT_DEVICE                   0x01
173 #define USB_DT_INTERFACE                0x04
174
175 static int dev_if_packed_info(struct udev_device *dev, char *ifs_str, size_t len)
176 {
177         char *filename = NULL;
178         int fd;
179         ssize_t size;
180         unsigned char buf[18 + 65535];
181         unsigned int pos, strpos;
182         struct usb_interface_descriptor {
183                 u_int8_t        bLength;
184                 u_int8_t        bDescriptorType;
185                 u_int8_t        bInterfaceNumber;
186                 u_int8_t        bAlternateSetting;
187                 u_int8_t        bNumEndpoints;
188                 u_int8_t        bInterfaceClass;
189                 u_int8_t        bInterfaceSubClass;
190                 u_int8_t        bInterfaceProtocol;
191                 u_int8_t        iInterface;
192         } __attribute__((packed));
193         int err = 0;
194
195         if (asprintf(&filename, "%s/descriptors", udev_device_get_syspath(dev)) < 0) {
196                 err = -1;
197                 goto out;
198         }
199         fd = open(filename, O_RDONLY);
200         if (fd < 0) {
201                 fprintf(stderr, "error opening USB device 'descriptors' file\n");
202                 err = -1;
203                 goto out;
204         }
205         size = read(fd, buf, sizeof(buf));
206         close(fd);
207         if (size < 18 || size == sizeof(buf)) {
208                 err = -1;
209                 goto out;
210         }
211
212         pos = 0;
213         strpos = 0;
214         while (pos < sizeof(buf) && strpos+7 < len) {
215                 struct usb_interface_descriptor *desc;
216                 char if_str[8];
217
218                 desc = (struct usb_interface_descriptor *) &buf[pos];
219                 if (desc->bLength < 3)
220                         break;
221                 pos += desc->bLength;
222
223                 if (desc->bDescriptorType != USB_DT_INTERFACE)
224                         continue;
225
226                 if (snprintf(if_str, 8, "%02x%02x%02x:",
227                              desc->bInterfaceClass,
228                              desc->bInterfaceSubClass,
229                              desc->bInterfaceProtocol) != 7)
230                         continue;
231
232                 if (strstr(ifs_str, if_str) != NULL)
233                         continue;
234
235                 memcpy(&ifs_str[strpos], if_str, 8),
236                 strpos += 7;
237         }
238 out:
239         free(filename);
240         return err;
241 }
242
243 /*
244  * A unique USB identification is generated like this:
245  *
246  * 1.) Get the USB device type from InterfaceClass and InterfaceSubClass
247  * 2.) If the device type is 'Mass-Storage/SPC-2' or 'Mass-Storage/RBC'
248  *     use the SCSI vendor and model as USB-Vendor and USB-model.
249  * 3.) Otherwise use the USB manufacturer and product as
250  *     USB-Vendor and USB-model. Any non-printable characters
251  *     in those strings will be skipped; a slash '/' will be converted
252  *     into a full stop '.'.
253  * 4.) If that fails, too, we will use idVendor and idProduct
254  *     as USB-Vendor and USB-model.
255  * 5.) The USB identification is the USB-vendor and USB-model
256  *     string concatenated with an underscore '_'.
257  * 6.) If the device supplies a serial number, this number
258  *     is concatenated with the identification with an underscore '_'.
259  */
260 static int usb_id(struct udev_device *dev)
261 {
262         struct udev *udev = udev_device_get_udev(dev);
263         struct udev_device *dev_interface = NULL;
264         struct udev_device *dev_usb = NULL;
265         const char *if_class, *if_subclass;
266         int if_class_num;
267         int protocol = 0;
268         const char *str;
269
270         dbg(udev, "syspath %s\n", udev_device_get_syspath(dev));
271
272         /* shortcut, if we are called directly for a "usb_device" type */
273         if (udev_device_get_devtype(dev) != NULL && strcmp(udev_device_get_devtype(dev), "usb_device") == 0) {
274                 dev_if_packed_info(dev, packed_if_str, sizeof(packed_if_str));
275                 dev_usb = dev;
276                 goto fallback;
277         }
278
279         /* usb interface directory */
280         dev_interface = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface");
281         if (dev_interface == NULL) {
282                 info(udev, "unable to access usb_interface device of '%s'\n",
283                      udev_device_get_syspath(dev));
284                 return 1;
285         }
286
287         ifnum = udev_device_get_sysattr_value(dev_interface, "bInterfaceNumber");
288         driver = udev_device_get_sysattr_value(dev_interface, "driver");
289
290         if_class = udev_device_get_sysattr_value(dev_interface, "bInterfaceClass");
291         if (!if_class) {
292                 info(udev, "%s: cannot get bInterfaceClass attribute\n",
293                      udev_device_get_sysname(dev));
294                 return 1;
295         }
296
297         if_class_num = strtoul(if_class, NULL, 16);
298         if (if_class_num == 8) {
299                 /* mass storage */
300                 if_subclass = udev_device_get_sysattr_value(dev_interface, "bInterfaceSubClass");
301                 if (if_subclass != NULL)
302                         protocol = set_usb_mass_storage_ifsubtype(type_str, if_subclass, sizeof(type_str)-1);
303         } else {
304                 set_usb_iftype(type_str, if_class_num, sizeof(type_str)-1);
305         }
306
307         info(udev, "%s: if_class %d protocol %d\n",
308              udev_device_get_syspath(dev_interface), if_class_num, protocol);
309
310         /* usb device directory */
311         dev_usb = udev_device_get_parent_with_subsystem_devtype(dev_interface, "usb", "usb_device");
312         if (!dev_usb) {
313                 info(udev, "unable to find parent 'usb' device of '%s'\n",
314                      udev_device_get_syspath(dev));
315                 return 1;
316         }
317
318         /* all interfaces of the device in a single string */
319         dev_if_packed_info(dev_usb, packed_if_str, sizeof(packed_if_str));
320
321         /* mass storage : SCSI or ATAPI */
322         if ((protocol == 6 || protocol == 2) && !use_usb_info) {
323                 struct udev_device *dev_scsi;
324                 const char *scsi_model, *scsi_vendor, *scsi_type, *scsi_rev;
325                 int host, bus, target, lun;
326
327                 /* get scsi device */
328                 dev_scsi = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
329                 if (dev_scsi == NULL) {
330                         info(udev, "unable to find parent 'scsi' device of '%s'\n",
331                              udev_device_get_syspath(dev));
332                         goto fallback;
333                 }
334                 if (sscanf(udev_device_get_sysname(dev_scsi), "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4) {
335                         info(udev, "invalid scsi device '%s'\n", udev_device_get_sysname(dev_scsi));
336                         goto fallback;
337                 }
338
339                 /* Generic SPC-2 device */
340                 scsi_vendor = udev_device_get_sysattr_value(dev_scsi, "vendor");
341                 if (!scsi_vendor) {
342                         info(udev, "%s: cannot get SCSI vendor attribute\n",
343                              udev_device_get_sysname(dev_scsi));
344                         goto fallback;
345                 }
346                 udev_util_encode_string(scsi_vendor, vendor_str_enc, sizeof(vendor_str_enc));
347                 udev_util_replace_whitespace(scsi_vendor, vendor_str, sizeof(vendor_str)-1);
348                 udev_util_replace_chars(vendor_str, NULL);
349
350                 scsi_model = udev_device_get_sysattr_value(dev_scsi, "model");
351                 if (!scsi_model) {
352                         info(udev, "%s: cannot get SCSI model attribute\n",
353                              udev_device_get_sysname(dev_scsi));
354                         goto fallback;
355                 }
356                 udev_util_encode_string(scsi_model, model_str_enc, sizeof(model_str_enc));
357                 udev_util_replace_whitespace(scsi_model, model_str, sizeof(model_str)-1);
358                 udev_util_replace_chars(model_str, NULL);
359
360                 scsi_type = udev_device_get_sysattr_value(dev_scsi, "type");
361                 if (!scsi_type) {
362                         info(udev, "%s: cannot get SCSI type attribute\n",
363                              udev_device_get_sysname(dev_scsi));
364                         goto fallback;
365                 }
366                 set_scsi_type(type_str, scsi_type, sizeof(type_str)-1);
367
368                 scsi_rev = udev_device_get_sysattr_value(dev_scsi, "rev");
369                 if (!scsi_rev) {
370                         info(udev, "%s: cannot get SCSI revision attribute\n",
371                              udev_device_get_sysname(dev_scsi));
372                         goto fallback;
373                 }
374                 udev_util_replace_whitespace(scsi_rev, revision_str, sizeof(revision_str)-1);
375                 udev_util_replace_chars(revision_str, NULL);
376
377                 /*
378                  * some broken devices have the same identifiers
379                  * for all luns, export the target:lun number
380                  */
381                 sprintf(instance_str, "%d:%d", target, lun);
382         }
383
384 fallback:
385         vendor_id = udev_device_get_sysattr_value(dev_usb, "idVendor");
386         product_id = udev_device_get_sysattr_value(dev_usb, "idProduct");
387
388         /* fallback to USB vendor & device */
389         if (vendor_str[0] == '\0') {
390                 const char *usb_vendor = NULL;
391
392                 if (!use_num_info)
393                         usb_vendor = udev_device_get_sysattr_value(dev_usb, "manufacturer");
394
395                 if (!usb_vendor)
396                         usb_vendor = vendor_id;
397
398                 if (!usb_vendor) {
399                         info(udev, "No USB vendor information available\n");
400                         return 1;
401                 }
402                 udev_util_encode_string(usb_vendor, vendor_str_enc, sizeof(vendor_str_enc));
403                 udev_util_replace_whitespace(usb_vendor, vendor_str, sizeof(vendor_str)-1);
404                 udev_util_replace_chars(vendor_str, NULL);
405         }
406
407         if (model_str[0] == '\0') {
408                 const char *usb_model = NULL;
409
410                 if (!use_num_info)
411                         usb_model = udev_device_get_sysattr_value(dev_usb, "product");
412
413                 if (!usb_model)
414                         usb_model = product_id;
415
416                 if (!usb_model) {
417                         dbg(udev, "No USB model information available\n");
418                         return 1;
419                 }
420                 udev_util_encode_string(usb_model, model_str_enc, sizeof(model_str_enc));
421                 udev_util_replace_whitespace(usb_model, model_str, sizeof(model_str)-1);
422                 udev_util_replace_chars(model_str, NULL);
423         }
424
425         if (revision_str[0] == '\0') {
426                 const char *usb_rev;
427
428                 usb_rev = udev_device_get_sysattr_value(dev_usb, "bcdDevice");
429                 if (usb_rev) {
430                         udev_util_replace_whitespace(usb_rev, revision_str, sizeof(revision_str)-1);
431                         udev_util_replace_chars(revision_str, NULL);
432                 }
433         }
434
435         if (serial_str[0] == '\0') {
436                 const char *usb_serial;
437
438                 usb_serial = udev_device_get_sysattr_value(dev_usb, "serial");
439                 if (usb_serial) {
440                         udev_util_replace_whitespace(usb_serial, serial_str, sizeof(serial_str)-1);
441                         udev_util_replace_chars(serial_str, NULL);
442                 }
443         }
444         return 0;
445 }
446
447 int main(int argc, char **argv)
448 {
449         static const struct option options[] = {
450                 { "usb-info", no_argument, NULL, 'u' },
451                 { "num-info", no_argument, NULL, 'n' },
452                 { "export", no_argument, NULL, 'x' },
453                 { "debug", no_argument, NULL, 'd' },
454                 { "help", no_argument, NULL, 'h' },
455                 {}
456         };
457         struct udev *udev;
458         struct udev_device *dev = NULL;
459         char syspath[UTIL_PATH_SIZE];
460         const char *devpath;
461         static int export;
462         int retval = 0;
463
464         udev = udev_new();
465         if (udev == NULL)
466                 goto exit;
467
468         logging_init("usb_id");
469         udev_set_log_fn(udev, log_fn);
470
471         while (1) {
472                 int option;
473
474                 option = getopt_long(argc, argv, "dnuxh", options, NULL);
475                 if (option == -1)
476                         break;
477
478                 switch (option) {
479                 case 'd':
480                         debug = 1;
481                         if (udev_get_log_priority(udev) < LOG_INFO)
482                                 udev_set_log_priority(udev, LOG_INFO);
483                         break;
484                 case 'n':
485                         use_num_info = 1;
486                         use_usb_info = 1;
487                         break;
488                 case 'u':
489                         use_usb_info = 1;
490                         break;
491                 case 'x':
492                         export = 1;
493                         break;
494                 case 'h':
495                         printf("Usage: usb_id [--usb-info] [--num-info] [--export] [--help] <devpath>\n"
496                                "  --usb-info  use usb strings instead\n"
497                                "  --num-info  use numerical values\n"
498                                "  --export    print values as environment keys\n"
499                                "  --help      print this help text\n\n");
500                 default:
501                         retval = 1;
502                         goto exit;
503                 }
504         }
505
506         devpath = argv[optind];
507         if (devpath == NULL) {
508                 fprintf(stderr, "No device specified\n");
509                 retval = 1;
510                 goto exit;
511         }
512
513         util_strlcpy(syspath, udev_get_sys_path(udev), sizeof(syspath));
514         util_strlcat(syspath, devpath, sizeof(syspath));
515         dev = udev_device_new_from_syspath(udev, syspath);
516         if (dev == NULL) {
517                 err(udev, "unable to access '%s'\n", devpath);
518                 return 1;
519         }
520
521         retval = usb_id(dev);
522         if (retval == 0) {
523                 char serial[256];
524
525                 util_strlcpy(serial, vendor_str, sizeof(serial));
526                 util_strlcat(serial, "_", sizeof(serial));
527                 util_strlcat(serial, model_str, sizeof(serial));
528                 if (serial_str[0] != '\0') {
529                         util_strlcat(serial, "_", sizeof(serial));
530                         util_strlcat(serial, serial_str, sizeof(serial));
531                 }
532                 if (instance_str[0] != '\0') {
533                         util_strlcat(serial, "-", sizeof(serial));
534                         util_strlcat(serial, instance_str, sizeof(serial));
535                 }
536
537                 if (export) {
538                         printf("ID_VENDOR=%s\n", vendor_str);
539                         printf("ID_VENDOR_ENC=%s\n", vendor_str_enc);
540                         printf("ID_VENDOR_ID=%s\n", vendor_id);
541                         printf("ID_MODEL=%s\n", model_str);
542                         printf("ID_MODEL_ENC=%s\n", model_str_enc);
543                         printf("ID_MODEL_ID=%s\n", product_id);
544                         printf("ID_REVISION=%s\n", revision_str);
545                         printf("ID_SERIAL=%s\n", serial);
546                         if (serial_str[0] != '\0')
547                                 printf("ID_SERIAL_SHORT=%s\n", serial_str);
548                         if (type_str[0] != '\0')
549                                 printf("ID_TYPE=%s\n", type_str);
550                         if (instance_str[0] != '\0')
551                                 printf("ID_INSTANCE=%s\n", instance_str);
552                         printf("ID_BUS=usb\n");
553                         if (packed_if_str[0] != '\0')
554                                 printf("ID_USB_INTERFACES=:%s\n", packed_if_str);
555                         if (ifnum != NULL)
556                                 printf("ID_USB_INTERFACE_NUM=%s\n", ifnum);
557                         if (driver != NULL)
558                                 printf("ID_USB_DRIVER=%s\n", driver);
559                 } else
560                         printf("%s\n", serial);
561         }
562
563 exit:
564         udev_device_unref(dev);
565         udev_unref(udev);
566         logging_close();
567         return retval;
568 }