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