chiark / gitweb /
libudev: device - remove udev_device_get_parent_with_subsystem
[elogind.git] / extras / scsi_id / scsi_id.c
1 /*
2  * scsi_id.c
3  *
4  * Main section of the scsi_id program
5  *
6  * Copyright (C) IBM Corp. 2003
7  * Copyright (C) SUSE Linux Products GmbH, 2006
8  *
9  * Author:
10  *      Patrick Mansfield<patmans@us.ibm.com>
11  *
12  *      This program is free software; you can redistribute it and/or modify it
13  *      under the terms of the GNU General Public License as published by the
14  *      Free Software Foundation version 2 of the License.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <signal.h>
21 #include <fcntl.h>
22 #include <errno.h>
23 #include <string.h>
24 #include <syslog.h>
25 #include <stdarg.h>
26 #include <ctype.h>
27 #include <getopt.h>
28 #include <sys/stat.h>
29
30 #include "../../udev/udev.h"
31 #include "scsi_id.h"
32
33 static const struct option options[] = {
34         { "device", required_argument, NULL, 'd' },
35         { "config", required_argument, NULL, 'f' },
36         { "page", required_argument, NULL, 'p' },
37         { "blacklisted", no_argument, NULL, 'b' },
38         { "whitelisted", no_argument, NULL, 'g' },
39         { "replace-whitespace", no_argument, NULL, 'u' },
40         { "sg-version", required_argument, NULL, 's' },
41         { "verbose", no_argument, NULL, 'v' },
42         { "version", no_argument, NULL, 'V' },
43         { "export", no_argument, NULL, 'x' },
44         { "help", no_argument, NULL, 'h' },
45         {}
46 };
47
48 static const char short_options[] = "d:f:ghip:uvVx";
49 static const char dev_short_options[] = "bgp:";
50
51 static int all_good;
52 static int dev_specified;
53 static char config_file[MAX_PATH_LEN] = SYSCONFDIR "/scsi_id.config";
54 static enum page_code default_page_code;
55 static int sg_version = 4;
56 static int use_stderr;
57 static int debug;
58 static int reformat_serial;
59 static int export;
60 static char vendor_str[64];
61 static char model_str[64];
62 static char revision_str[16];
63 static char type_str[16];
64
65 static void log_fn(struct udev *udev, int priority,
66                    const char *file, int line, const char *fn,
67                    const char *format, va_list args)
68 {
69         vsyslog(priority, format, args);
70 }
71
72 static void set_type(const char *from, char *to, size_t len)
73 {
74         int type_num;
75         char *eptr;
76         char *type = "generic";
77
78         type_num = strtoul(from, &eptr, 0);
79         if (eptr != from) {
80                 switch (type_num) {
81                 case 0:
82                         type = "disk";
83                         break;
84                 case 1:
85                         type = "tape";
86                         break;
87                 case 4:
88                         type = "optical";
89                         break;
90                 case 5:
91                         type = "cd";
92                         break;
93                 case 7:
94                         type = "optical";
95                         break;
96                 case 0xe:
97                         type = "disk";
98                         break;
99                 case 0xf:
100                         type = "optical";
101                         break;
102                 default:
103                         break;
104                 }
105         }
106         util_strlcpy(to, type, len);
107 }
108
109 /*
110  * get_value:
111  *
112  * buf points to an '=' followed by a quoted string ("foo") or a string ending
113  * with a space or ','.
114  *
115  * Return a pointer to the NUL terminated string, returns NULL if no
116  * matches.
117  */
118 static char *get_value(char **buffer)
119 {
120         static char *quote_string = "\"\n";
121         static char *comma_string = ",\n";
122         char *val;
123         char *end;
124
125         if (**buffer == '"') {
126                 /*
127                  * skip leading quote, terminate when quote seen
128                  */
129                 (*buffer)++;
130                 end = quote_string;
131         } else {
132                 end = comma_string;
133         }
134         val = strsep(buffer, end);
135         if (val && end == quote_string)
136                 /*
137                  * skip trailing quote
138                  */
139                 (*buffer)++;
140
141         while (isspace(**buffer))
142                 (*buffer)++;
143
144         return val;
145 }
146
147 static int argc_count(char *opts)
148 {
149         int i = 0;
150         while (*opts != '\0')
151                 if (*opts++ == ' ')
152                         i++;
153         return i;
154 }
155
156 /*
157  * get_file_options:
158  *
159  * If vendor == NULL, find a line in the config file with only "OPTIONS=";
160  * if vendor and model are set find the first OPTIONS line in the config
161  * file that matches. Set argc and argv to match the OPTIONS string.
162  *
163  * vendor and model can end in '\n'.
164  */
165 static int get_file_options(struct udev *udev,
166                             const char *vendor, const char *model,
167                             int *argc, char ***newargv)
168 {
169         char *buffer;
170         FILE *fd;
171         char *buf;
172         char *str1;
173         char *vendor_in, *model_in, *options_in; /* read in from file */
174         int lineno;
175         int c;
176         int retval = 0;
177
178         dbg(udev, "vendor='%s'; model='%s'\n", vendor, model);
179         fd = fopen(config_file, "r");
180         if (fd == NULL) {
181                 dbg(udev, "can't open %s\n", config_file);
182                 if (errno == ENOENT) {
183                         return 1;
184                 } else {
185                         err(udev, "can't open %s: %s\n", config_file, strerror(errno));
186                         return -1;
187                 }
188         }
189
190         /*
191          * Allocate a buffer rather than put it on the stack so we can
192          * keep it around to parse any options (any allocated newargv
193          * points into this buffer for its strings).
194          */
195         buffer = malloc(MAX_BUFFER_LEN);
196         if (!buffer) {
197                 err(udev, "can't allocate memory\n");
198                 return -1;
199         }
200
201         *newargv = NULL;
202         lineno = 0;
203         while (1) {
204                 vendor_in = model_in = options_in = NULL;
205
206                 buf = fgets(buffer, MAX_BUFFER_LEN, fd);
207                 if (buf == NULL)
208                         break;
209                 lineno++;
210                 if (buf[strlen(buffer) - 1] != '\n') {
211                         err(udev, "Config file line %d too long\n", lineno);
212                         break;
213                 }
214
215                 while (isspace(*buf))
216                         buf++;
217
218                 /* blank or all whitespace line */
219                 if (*buf == '\0')
220                         continue;
221
222                 /* comment line */
223                 if (*buf == '#')
224                         continue;
225
226                 dbg(udev, "lineno %d: '%s'\n", lineno, buf);
227                 str1 = strsep(&buf, "=");
228                 if (str1 && strcasecmp(str1, "VENDOR") == 0) {
229                         str1 = get_value(&buf);
230                         if (!str1) {
231                                 retval = -1;
232                                 break;
233                         }
234                         vendor_in = str1;
235
236                         str1 = strsep(&buf, "=");
237                         if (str1 && strcasecmp(str1, "MODEL") == 0) {
238                                 str1 = get_value(&buf);
239                                 if (!str1) {
240                                         retval = -1;
241                                         break;
242                                 }
243                                 model_in = str1;
244                                 str1 = strsep(&buf, "=");
245                         }
246                 }
247
248                 if (str1 && strcasecmp(str1, "OPTIONS") == 0) {
249                         str1 = get_value(&buf);
250                         if (!str1) {
251                                 retval = -1;
252                                 break;
253                         }
254                         options_in = str1;
255                 }
256                 dbg(udev, "config file line %d:\n"
257                         " vendor '%s'; model '%s'; options '%s'\n",
258                         lineno, vendor_in, model_in, options_in);
259                 /*
260                  * Only allow: [vendor=foo[,model=bar]]options=stuff
261                  */
262                 if (!options_in || (!vendor_in && model_in)) {
263                         err(udev, "Error parsing config file line %d '%s'\n", lineno, buffer);
264                         retval = -1;
265                         break;
266                 }
267                 if (vendor == NULL) {
268                         if (vendor_in == NULL) {
269                                 dbg(udev, "matched global option\n");
270                                 break;
271                         }
272                 } else if ((vendor_in && strncmp(vendor, vendor_in,
273                                                  strlen(vendor_in)) == 0) &&
274                            (!model_in || (strncmp(model, model_in,
275                                                   strlen(model_in)) == 0))) {
276                                 /*
277                                  * Matched vendor and optionally model.
278                                  *
279                                  * Note: a short vendor_in or model_in can
280                                  * give a partial match (that is FOO
281                                  * matches FOOBAR).
282                                  */
283                                 dbg(udev, "matched vendor/model\n");
284                                 break;
285                 } else {
286                         dbg(udev, "no match\n");
287                 }
288         }
289
290         if (retval == 0) {
291                 if (vendor_in != NULL || model_in != NULL ||
292                     options_in != NULL) {
293                         /*
294                          * Something matched. Allocate newargv, and store
295                          * values found in options_in.
296                          */
297                         strcpy(buffer, options_in);
298                         c = argc_count(buffer) + 2;
299                         *newargv = calloc(c, sizeof(**newargv));
300                         if (!*newargv) {
301                                 err(udev, "can't allocate memory\n");
302                                 retval = -1;
303                         } else {
304                                 *argc = c;
305                                 c = 0;
306                                 /*
307                                  * argv[0] at 0 is skipped by getopt, but
308                                  * store the buffer address there for
309                                  * later freeing
310                                  */
311                                 (*newargv)[c] = buffer;
312                                 for (c = 1; c < *argc; c++)
313                                         (*newargv)[c] = strsep(&buffer, " \t");
314                         }
315                 } else {
316                         /* No matches  */
317                         retval = 1;
318                 }
319         }
320         if (retval != 0)
321                 free(buffer);
322         fclose(fd);
323         return retval;
324 }
325
326 static int set_options(struct udev *udev,
327                        int argc, char **argv, const char *short_opts,
328                        char *maj_min_dev)
329 {
330         int option;
331
332         /*
333          * optind is a global extern used by getopt. Since we can call
334          * set_options twice (once for command line, and once for config
335          * file) we have to reset this back to 1.
336          */
337         optind = 1;
338         while (1) {
339                 option = getopt_long(argc, argv, short_opts, options, NULL);
340                 if (option == -1)
341                         break;
342
343                 if (optarg)
344                         dbg(udev, "option '%c' arg '%s'\n", option, optarg);
345                 else
346                         dbg(udev, "option '%c'\n", option);
347
348                 switch (option) {
349                 case 'b':
350                         all_good = 0;
351                         break;
352
353                 case 'd':
354                         dev_specified = 1;
355                         util_strlcpy(maj_min_dev, optarg, MAX_PATH_LEN);
356                         break;
357
358                 case 'e':
359                         use_stderr = 1;
360                         break;
361
362                 case 'f':
363                         util_strlcpy(config_file, optarg, MAX_PATH_LEN);
364                         break;
365
366                 case 'g':
367                         all_good = 1;
368                         break;
369
370                 case 'h':
371                         printf("Usage: scsi_id OPTIONS <device>\n"
372                                "  --device=                     device node for SG_IO commands\n"
373                                "  --config=                     location of config file\n"
374                                "  --page=0x80|0x83|pre-spc3-83  SCSI page (0x80, 0x83, pre-spc3-83)\n"
375                                "  --sg-version=3|4              use SGv3 or SGv4\n"
376                                "  --blacklisted                 threat device as blacklisted\n"
377                                "  --whitelisted                 threat device as whitelisted\n"
378                                "  --replace-whitespace          replace all whitespaces by underscores\n"
379                                "  --verbose                     verbose logging\n"
380                                "  --version                     print version\n"
381                                "  --export                      print values as environment keys\n"
382                                "  --help                        print this help text\n\n");
383                         exit(0);
384
385                 case 'p':
386                         if (strcmp(optarg, "0x80") == 0) {
387                                 default_page_code = PAGE_80;
388                         } else if (strcmp(optarg, "0x83") == 0) {
389                                 default_page_code = PAGE_83;
390                         } else if (strcmp(optarg, "pre-spc3-83") == 0) {
391                                 default_page_code = PAGE_83_PRE_SPC3; 
392                         } else {
393                                 err(udev, "Unknown page code '%s'\n", optarg);
394                                 return -1;
395                         }
396                         break;
397
398                 case 's':
399                         sg_version = atoi(optarg);
400                         if (sg_version < 3 || sg_version > 4) {
401                                 err(udev, "Unknown SG version '%s'\n", optarg);
402                                 return -1;
403                         }
404                         break;
405
406                 case 'u':
407                         reformat_serial = 1;
408                         break;
409
410                 case 'x':
411                         export = 1;
412                         break;
413
414                 case 'v':
415                         debug++;
416                         break;
417
418                 case 'V':
419                         printf("%s\n", VERSION);
420                         exit(0);
421                         break;
422
423                 default:
424                         exit(1);
425                 }
426         }
427         if (optind < argc && !dev_specified) {
428                 dev_specified = 1;
429                 util_strlcpy(maj_min_dev, argv[optind], MAX_PATH_LEN);
430         }
431         return 0;
432 }
433
434 static int per_dev_options(struct udev *udev,
435                            struct scsi_id_device *dev_scsi, int *good_bad, int *page_code)
436 {
437         int retval;
438         int newargc;
439         char **newargv = NULL;
440         int option;
441
442         *good_bad = all_good;
443         *page_code = default_page_code;
444
445         retval = get_file_options(udev, vendor_str, model_str, &newargc, &newargv);
446
447         optind = 1; /* reset this global extern */
448         while (retval == 0) {
449                 option = getopt_long(newargc, newargv, dev_short_options, options, NULL);
450                 if (option == -1)
451                         break;
452
453                 if (optarg)
454                         dbg(udev, "option '%c' arg '%s'\n", option, optarg);
455                 else
456                         dbg(udev, "option '%c'\n", option);
457
458                 switch (option) {
459                 case 'b':
460                         *good_bad = 0;
461                         break;
462
463                 case 'g':
464                         *good_bad = 1;
465                         break;
466
467                 case 'p':
468                         if (strcmp(optarg, "0x80") == 0) {
469                                 *page_code = PAGE_80;
470                         } else if (strcmp(optarg, "0x83") == 0) {
471                                 *page_code = PAGE_83;
472                         } else if (strcmp(optarg, "pre-spc3-83") == 0) {
473                                 *page_code = PAGE_83_PRE_SPC3; 
474                         } else {
475                                 err(udev, "Unknown page code '%s'\n", optarg);
476                                 retval = -1;
477                         }
478                         break;
479
480                 default:
481                         err(udev, "Unknown or bad option '%c' (0x%x)\n", option, option);
482                         retval = -1;
483                         break;
484                 }
485         }
486
487         if (newargv) {
488                 free(newargv[0]);
489                 free(newargv);
490         }
491         return retval;
492 }
493
494 static int set_inq_values(struct udev *udev, struct scsi_id_device *dev_scsi, const char *path)
495 {
496         int retval;
497
498         dev_scsi->use_sg = sg_version;
499
500         retval = scsi_std_inquiry(udev, dev_scsi, path);
501         if (retval)
502                 return retval;
503
504         udev_util_replace_whitespace(dev_scsi->vendor, vendor_str, sizeof(vendor_str));
505         udev_util_replace_chars(vendor_str, NULL);
506         udev_util_replace_whitespace(dev_scsi->model, model_str, sizeof(model_str));
507         udev_util_replace_chars(model_str, NULL);
508         set_type(dev_scsi->type, type_str, sizeof(type_str));
509         udev_util_replace_whitespace(dev_scsi->revision, revision_str, sizeof(revision_str));
510         udev_util_replace_chars(revision_str, NULL);
511         return 0;
512 }
513
514 /*
515  * format_serial: replace to whitespaces by underscores for calling
516  * programs that use the serial for device naming (multipath, Suse
517  * naming, etc...)
518  */
519 static void format_serial(char *serial)
520 {
521         char *p = serial, *q;
522
523         q = p;
524         while (*p != '\0') {
525                 if (isspace(*p)) {
526                         if (q > serial && q[-1] != '_') {
527                                 *q = '_';
528                                 q++;
529                         }
530                 } else {
531                         *q = *p;
532                         q++;
533                 }
534                 p++;
535         }
536         *q = '\0';
537 }
538
539 /*
540  * scsi_id: try to get an id, if one is found, printf it to stdout.
541  * returns a value passed to exit() - 0 if printed an id, else 1.
542  */
543 static int scsi_id(struct udev *udev, char *maj_min_dev)
544 {
545         struct scsi_id_device dev_scsi;
546         int good_dev;
547         int page_code;
548         int retval = 0;
549
550         memset(&dev_scsi, 0x00, sizeof(struct scsi_id_device));
551
552         if (set_inq_values(udev, &dev_scsi, maj_min_dev) < 0) {
553                 retval = 1;
554                 goto out;
555         }
556
557         /* get per device (vendor + model) options from the config file */
558         per_dev_options(udev, &dev_scsi, &good_dev, &page_code);
559         dbg(udev, "per dev options: good %d; page code 0x%x\n", good_dev, page_code);
560         if (!good_dev) {
561                 retval = 1;
562                 goto out;
563         }
564
565         /* read serial number from mode pages (no values for optical drives) */
566         scsi_get_serial(udev, &dev_scsi, maj_min_dev, page_code, MAX_SERIAL_LEN);
567
568         if (export) {
569                 char serial_str[MAX_SERIAL_LEN];
570
571                 printf("ID_VENDOR=%s\n", vendor_str);
572                 printf("ID_MODEL=%s\n", model_str);
573                 printf("ID_REVISION=%s\n", revision_str);
574                 printf("ID_TYPE=%s\n", type_str);
575                 if (dev_scsi.serial[0] != '\0') {
576                         udev_util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
577                         udev_util_replace_chars(serial_str, NULL);
578                         printf("ID_SERIAL=%s\n", serial_str);
579                         udev_util_replace_whitespace(dev_scsi.serial_short, serial_str, sizeof(serial_str));
580                         udev_util_replace_chars(serial_str, NULL);
581                         printf("ID_SERIAL_SHORT=%s\n", serial_str);
582                 }
583                 goto out;
584         }
585
586         if (dev_scsi.serial[0] == '\0') {
587                 retval = 1;
588                 goto out;
589         }
590         if (reformat_serial)
591                 format_serial(dev_scsi.serial);
592         printf("%s\n", dev_scsi.serial);
593 out:
594         return retval;
595 }
596
597 int main(int argc, char **argv)
598 {
599         struct udev *udev;
600         int retval = 0;
601         char maj_min_dev[MAX_PATH_LEN];
602         int newargc;
603         char **newargv;
604
605         udev = udev_new();
606         if (udev == NULL)
607                 goto exit;
608
609         logging_init("scsi_id");
610         udev_set_log_fn(udev, log_fn);
611
612         /*
613          * Get config file options.
614          */
615         newargv = NULL;
616         retval = get_file_options(udev, NULL, NULL, &newargc, &newargv);
617         if (retval < 0) {
618                 retval = 1;
619                 goto exit;
620         }
621         if (newargv && (retval == 0)) {
622                 if (set_options(udev, newargc, newargv, short_options, maj_min_dev) < 0) {
623                         retval = 2;
624                         goto exit;
625                 }
626                 free(newargv);
627         }
628
629         /*
630          * Get command line options (overriding any config file settings).
631          */
632         if (set_options(udev, argc, argv, short_options, maj_min_dev) < 0)
633                 exit(1);
634
635         if (!dev_specified) {
636                 err(udev, "no device specified\n");
637                 retval = 1;
638                 goto exit;
639         }
640
641         retval = scsi_id(udev, maj_min_dev);
642
643 exit:
644         udev_unref(udev);
645         logging_close();
646         return retval;
647 }