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