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