chiark / gitweb /
use more efficient string copying
[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_strscpy(to, len, type);
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_strscpy(to, len, type);
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
269         dbg(udev, "syspath %s\n", udev_device_get_syspath(dev));
270
271         /* shortcut, if we are called directly for a "usb_device" type */
272         if (udev_device_get_devtype(dev) != NULL && strcmp(udev_device_get_devtype(dev), "usb_device") == 0) {
273                 dev_if_packed_info(dev, packed_if_str, sizeof(packed_if_str));
274                 dev_usb = dev;
275                 goto fallback;
276         }
277
278         /* usb interface directory */
279         dev_interface = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface");
280         if (dev_interface == NULL) {
281                 info(udev, "unable to access usb_interface device of '%s'\n",
282                      udev_device_get_syspath(dev));
283                 return 1;
284         }
285
286         ifnum = udev_device_get_sysattr_value(dev_interface, "bInterfaceNumber");
287         driver = udev_device_get_sysattr_value(dev_interface, "driver");
288
289         if_class = udev_device_get_sysattr_value(dev_interface, "bInterfaceClass");
290         if (!if_class) {
291                 info(udev, "%s: cannot get bInterfaceClass attribute\n",
292                      udev_device_get_sysname(dev));
293                 return 1;
294         }
295
296         if_class_num = strtoul(if_class, NULL, 16);
297         if (if_class_num == 8) {
298                 /* mass storage */
299                 if_subclass = udev_device_get_sysattr_value(dev_interface, "bInterfaceSubClass");
300                 if (if_subclass != NULL)
301                         protocol = set_usb_mass_storage_ifsubtype(type_str, if_subclass, sizeof(type_str)-1);
302         } else {
303                 set_usb_iftype(type_str, if_class_num, sizeof(type_str)-1);
304         }
305
306         info(udev, "%s: if_class %d protocol %d\n",
307              udev_device_get_syspath(dev_interface), if_class_num, protocol);
308
309         /* usb device directory */
310         dev_usb = udev_device_get_parent_with_subsystem_devtype(dev_interface, "usb", "usb_device");
311         if (!dev_usb) {
312                 info(udev, "unable to find parent 'usb' device of '%s'\n",
313                      udev_device_get_syspath(dev));
314                 return 1;
315         }
316
317         /* all interfaces of the device in a single string */
318         dev_if_packed_info(dev_usb, packed_if_str, sizeof(packed_if_str));
319
320         /* mass storage : SCSI or ATAPI */
321         if ((protocol == 6 || protocol == 2) && !use_usb_info) {
322                 struct udev_device *dev_scsi;
323                 const char *scsi_model, *scsi_vendor, *scsi_type, *scsi_rev;
324                 int host, bus, target, lun;
325
326                 /* get scsi device */
327                 dev_scsi = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
328                 if (dev_scsi == NULL) {
329                         info(udev, "unable to find parent 'scsi' device of '%s'\n",
330                              udev_device_get_syspath(dev));
331                         goto fallback;
332                 }
333                 if (sscanf(udev_device_get_sysname(dev_scsi), "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4) {
334                         info(udev, "invalid scsi device '%s'\n", udev_device_get_sysname(dev_scsi));
335                         goto fallback;
336                 }
337
338                 /* Generic SPC-2 device */
339                 scsi_vendor = udev_device_get_sysattr_value(dev_scsi, "vendor");
340                 if (!scsi_vendor) {
341                         info(udev, "%s: cannot get SCSI vendor attribute\n",
342                              udev_device_get_sysname(dev_scsi));
343                         goto fallback;
344                 }
345                 udev_util_encode_string(scsi_vendor, vendor_str_enc, sizeof(vendor_str_enc));
346                 udev_util_replace_whitespace(scsi_vendor, vendor_str, sizeof(vendor_str)-1);
347                 udev_util_replace_chars(vendor_str, NULL);
348
349                 scsi_model = udev_device_get_sysattr_value(dev_scsi, "model");
350                 if (!scsi_model) {
351                         info(udev, "%s: cannot get SCSI model attribute\n",
352                              udev_device_get_sysname(dev_scsi));
353                         goto fallback;
354                 }
355                 udev_util_encode_string(scsi_model, model_str_enc, sizeof(model_str_enc));
356                 udev_util_replace_whitespace(scsi_model, model_str, sizeof(model_str)-1);
357                 udev_util_replace_chars(model_str, NULL);
358
359                 scsi_type = udev_device_get_sysattr_value(dev_scsi, "type");
360                 if (!scsi_type) {
361                         info(udev, "%s: cannot get SCSI type attribute\n",
362                              udev_device_get_sysname(dev_scsi));
363                         goto fallback;
364                 }
365                 set_scsi_type(type_str, scsi_type, sizeof(type_str)-1);
366
367                 scsi_rev = udev_device_get_sysattr_value(dev_scsi, "rev");
368                 if (!scsi_rev) {
369                         info(udev, "%s: cannot get SCSI revision attribute\n",
370                              udev_device_get_sysname(dev_scsi));
371                         goto fallback;
372                 }
373                 udev_util_replace_whitespace(scsi_rev, revision_str, sizeof(revision_str)-1);
374                 udev_util_replace_chars(revision_str, NULL);
375
376                 /*
377                  * some broken devices have the same identifiers
378                  * for all luns, export the target:lun number
379                  */
380                 sprintf(instance_str, "%d:%d", target, lun);
381         }
382
383 fallback:
384         vendor_id = udev_device_get_sysattr_value(dev_usb, "idVendor");
385         product_id = udev_device_get_sysattr_value(dev_usb, "idProduct");
386
387         /* fallback to USB vendor & device */
388         if (vendor_str[0] == '\0') {
389                 const char *usb_vendor = NULL;
390
391                 if (!use_num_info)
392                         usb_vendor = udev_device_get_sysattr_value(dev_usb, "manufacturer");
393
394                 if (!usb_vendor)
395                         usb_vendor = vendor_id;
396
397                 if (!usb_vendor) {
398                         info(udev, "No USB vendor information available\n");
399                         return 1;
400                 }
401                 udev_util_encode_string(usb_vendor, vendor_str_enc, sizeof(vendor_str_enc));
402                 udev_util_replace_whitespace(usb_vendor, vendor_str, sizeof(vendor_str)-1);
403                 udev_util_replace_chars(vendor_str, NULL);
404         }
405
406         if (model_str[0] == '\0') {
407                 const char *usb_model = NULL;
408
409                 if (!use_num_info)
410                         usb_model = udev_device_get_sysattr_value(dev_usb, "product");
411
412                 if (!usb_model)
413                         usb_model = product_id;
414
415                 if (!usb_model) {
416                         dbg(udev, "No USB model information available\n");
417                         return 1;
418                 }
419                 udev_util_encode_string(usb_model, model_str_enc, sizeof(model_str_enc));
420                 udev_util_replace_whitespace(usb_model, model_str, sizeof(model_str)-1);
421                 udev_util_replace_chars(model_str, NULL);
422         }
423
424         if (revision_str[0] == '\0') {
425                 const char *usb_rev;
426
427                 usb_rev = udev_device_get_sysattr_value(dev_usb, "bcdDevice");
428                 if (usb_rev) {
429                         udev_util_replace_whitespace(usb_rev, revision_str, sizeof(revision_str)-1);
430                         udev_util_replace_chars(revision_str, NULL);
431                 }
432         }
433
434         if (serial_str[0] == '\0') {
435                 const char *usb_serial;
436
437                 usb_serial = udev_device_get_sysattr_value(dev_usb, "serial");
438                 if (usb_serial) {
439                         udev_util_replace_whitespace(usb_serial, serial_str, sizeof(serial_str)-1);
440                         udev_util_replace_chars(serial_str, NULL);
441                 }
442         }
443         return 0;
444 }
445
446 int main(int argc, char **argv)
447 {
448         static const struct option options[] = {
449                 { "usb-info", no_argument, NULL, 'u' },
450                 { "num-info", no_argument, NULL, 'n' },
451                 { "export", no_argument, NULL, 'x' },
452                 { "debug", no_argument, NULL, 'd' },
453                 { "help", no_argument, NULL, 'h' },
454                 {}
455         };
456         struct udev *udev;
457         struct udev_device *dev = NULL;
458         char syspath[UTIL_PATH_SIZE];
459         const char *devpath;
460         static int export;
461         int retval = 0;
462
463         udev = udev_new();
464         if (udev == NULL)
465                 goto exit;
466
467         logging_init("usb_id");
468         udev_set_log_fn(udev, log_fn);
469
470         while (1) {
471                 int option;
472
473                 option = getopt_long(argc, argv, "dnuxh", options, NULL);
474                 if (option == -1)
475                         break;
476
477                 switch (option) {
478                 case 'd':
479                         debug = 1;
480                         if (udev_get_log_priority(udev) < LOG_INFO)
481                                 udev_set_log_priority(udev, LOG_INFO);
482                         break;
483                 case 'n':
484                         use_num_info = 1;
485                         use_usb_info = 1;
486                         break;
487                 case 'u':
488                         use_usb_info = 1;
489                         break;
490                 case 'x':
491                         export = 1;
492                         break;
493                 case 'h':
494                         printf("Usage: usb_id [--usb-info] [--num-info] [--export] [--help] <devpath>\n"
495                                "  --usb-info  use usb strings instead\n"
496                                "  --num-info  use numerical values\n"
497                                "  --export    print values as environment keys\n"
498                                "  --help      print this help text\n\n");
499                 default:
500                         retval = 1;
501                         goto exit;
502                 }
503         }
504
505         devpath = argv[optind];
506         if (devpath == NULL) {
507                 fprintf(stderr, "No device specified\n");
508                 retval = 1;
509                 goto exit;
510         }
511
512         util_strscpyl(syspath, sizeof(syspath), udev_get_sys_path(udev), devpath, NULL);
513         dev = udev_device_new_from_syspath(udev, syspath);
514         if (dev == NULL) {
515                 err(udev, "unable to access '%s'\n", devpath);
516                 return 1;
517         }
518
519         retval = usb_id(dev);
520         if (retval == 0) {
521                 char serial[256];
522                 size_t l;
523                 char *s;
524
525                 s = serial;
526                 l = util_strpcpyl(&s, sizeof(serial), vendor_str, "_", model_str, NULL);
527                 if (serial_str[0] != '\0')
528                         l = util_strpcpyl(&s, l, "_", serial_str, NULL);
529                 if (instance_str[0] != '\0')
530                         util_strpcpyl(&s, l, "-", instance_str, NULL);
531
532                 if (export) {
533                         printf("ID_VENDOR=%s\n", vendor_str);
534                         printf("ID_VENDOR_ENC=%s\n", vendor_str_enc);
535                         printf("ID_VENDOR_ID=%s\n", vendor_id);
536                         printf("ID_MODEL=%s\n", model_str);
537                         printf("ID_MODEL_ENC=%s\n", model_str_enc);
538                         printf("ID_MODEL_ID=%s\n", product_id);
539                         printf("ID_REVISION=%s\n", revision_str);
540                         printf("ID_SERIAL=%s\n", serial);
541                         if (serial_str[0] != '\0')
542                                 printf("ID_SERIAL_SHORT=%s\n", serial_str);
543                         if (type_str[0] != '\0')
544                                 printf("ID_TYPE=%s\n", type_str);
545                         if (instance_str[0] != '\0')
546                                 printf("ID_INSTANCE=%s\n", instance_str);
547                         printf("ID_BUS=usb\n");
548                         if (packed_if_str[0] != '\0')
549                                 printf("ID_USB_INTERFACES=:%s\n", packed_if_str);
550                         if (ifnum != NULL)
551                                 printf("ID_USB_INTERFACE_NUM=%s\n", ifnum);
552                         if (driver != NULL)
553                                 printf("ID_USB_DRIVER=%s\n", driver);
554                 } else
555                         printf("%s\n", serial);
556         }
557
558 exit:
559         udev_device_unref(dev);
560         udev_unref(udev);
561         logging_close();
562         return retval;
563 }