chiark / gitweb /
4f0233ed0d6a9a7b44a31ec15378dbe57f99b0d8
[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         { "prefix-bus-id", 0, NULL, 'i' },
41         { "replace-whitespace", 0, NULL, 'u' },
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 int display_bus_id;
56 static enum page_code default_page_code;
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                         info("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                         info("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                 SCSI page (0x80, 0x83, pre-spc3-83)\n"
427                                "  --blacklisted          threat device as blacklisted\n"
428                                "  --whitelisted          threat device as whitelisted\n"
429                                "  --prefix-bus-id        prefix SCSI bus id\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 'i':
438                         display_bus_id = 1;
439                         break;
440
441                 case 'p':
442                         if (strcmp(optarg, "0x80") == 0) {
443                                 default_page_code = PAGE_80;
444                         } else if (strcmp(optarg, "0x83") == 0) {
445                                 default_page_code = PAGE_83;
446                         } else if (strcmp(optarg, "pre-spc3-83") == 0) {
447                                 default_page_code = PAGE_83_PRE_SPC3; 
448                         } else {
449                                 info("Unknown page code '%s'\n", optarg);
450                                 return -1;
451                         }
452                         break;
453
454                 case 'u':
455                         reformat_serial = 1;
456                         break;
457
458                 case 'x':
459                         export = 1;
460                         break;
461
462                 case 'v':
463                         debug++;
464                         break;
465
466                 case 'V':
467                         printf("%s\n", SCSI_ID_VERSION);
468                         exit(0);
469                         break;
470
471                 default:
472                         exit(1);
473                 }
474         }
475         if (optind < argc && !dev_specified) {
476                 dev_specified = 1;
477                 strncpy(maj_min_dev, argv[optind], MAX_PATH_LEN);
478                 maj_min_dev[MAX_PATH_LEN-1] = '\0';
479         }
480         return 0;
481 }
482
483 static int per_dev_options(struct scsi_id_device *dev_scsi, int *good_bad, int *page_code)
484 {
485         int retval;
486         int newargc;
487         char **newargv = NULL;
488         int option;
489
490         *good_bad = all_good;
491         *page_code = default_page_code;
492
493         retval = get_file_options(vendor_str, model_str, &newargc, &newargv);
494
495         optind = 1; /* reset this global extern */
496         while (retval == 0) {
497                 option = getopt_long(newargc, newargv, dev_short_options, options, NULL);
498                 if (option == -1)
499                         break;
500
501                 if (optarg)
502                         dbg("option '%c' arg '%s'\n", option, optarg);
503                 else
504                         dbg("option '%c'\n", option);
505
506                 switch (option) {
507                 case 'b':
508                         *good_bad = 0;
509                         break;
510
511                 case 'g':
512                         *good_bad = 1;
513                         break;
514
515                 case 'p':
516                         if (strcmp(optarg, "0x80") == 0) {
517                                 *page_code = PAGE_80;
518                         } else if (strcmp(optarg, "0x83") == 0) {
519                                 *page_code = PAGE_83;
520                         } else if (strcmp(optarg, "pre-spc3-83") == 0) {
521                                 *page_code = PAGE_83_PRE_SPC3; 
522                         } else {
523                                 info("Unknown page code '%s'\n", optarg);
524                                 retval = -1;
525                         }
526                         break;
527
528                 default:
529                         info("Unknown or bad option '%c' (0x%x)\n", option, option);
530                         retval = -1;
531                         break;
532                 }
533         }
534
535         if (newargv) {
536                 free(newargv[0]);
537                 free(newargv);
538         }
539         return retval;
540 }
541
542 static int set_inq_values(struct scsi_id_device *dev_scsi, const char *path)
543 {
544         int retval;
545
546         retval = scsi_std_inquiry(dev_scsi, path);
547         if (retval)
548             return retval;
549
550         set_str(vendor_str, dev_scsi->vendor, 8);
551         set_str(model_str, dev_scsi->model, 16);
552         set_type(type_str, dev_scsi->type, sizeof(type_str) - 1);
553         set_str(revision_str, dev_scsi->revision, sizeof(revision_str) -1);
554
555         return 0;
556 }
557
558 /*
559  * format_serial: replace to whitespaces by underscores for calling
560  * programs that use the serial for device naming (multipath, Suse
561  * naming, etc...)
562  */
563 static void format_serial(char *serial)
564 {
565         char *p = serial, *q;
566
567         q = p;
568         while (*p != '\0') {
569                 if (isspace(*p)) {
570                         if (q > serial && q[-1] != '_') {
571                                 *q = '_';
572                                 q++;
573                         }
574                 } else {
575                         *q = *p;
576                         q++;
577                 }
578                 p++;
579         }
580         *q = '\0';
581 }
582
583 /*
584  * scsi_id: try to get an id, if one is found, printf it to stdout.
585  * returns a value passed to exit() - 0 if printed an id, else 1. This
586  * could be expanded, for example, if we want to report a failure like no
587  * memory etc. return 2, and return 1 for expected cases (like broken
588  * device found) that do not print an id.
589  */
590 static int scsi_id(char *maj_min_dev)
591 {
592         int retval;
593         struct scsi_id_device dev_scsi;
594         int good_dev;
595         int page_code;
596         char serial_short[MAX_SERIAL_LEN] = "";
597
598         set_inq_values(&dev_scsi, maj_min_dev);
599
600         /* get per device (vendor + model) options from the config file */
601         retval = per_dev_options(&dev_scsi, &good_dev, &page_code);
602         dbg("per dev options: good %d; page code 0x%x\n", good_dev, page_code);
603
604         if (!good_dev) {
605                 retval = 1;
606         } else if (scsi_get_serial(&dev_scsi, maj_min_dev, page_code,
607                                    serial_short, MAX_SERIAL_LEN)) {
608                 retval = 1;
609         } else {
610                 retval = 0;
611         }
612         if (!retval) {
613                 if (export) {
614                         char serial_str[MAX_SERIAL_LEN];
615
616                         printf("ID_VENDOR=%s\n", vendor_str);
617                         printf("ID_MODEL=%s\n", model_str);
618                         printf("ID_REVISION=%s\n", revision_str);
619                         set_str(serial_str, dev_scsi.serial, sizeof(serial_str));
620                         printf("ID_SERIAL=%s\n", serial_str);
621                         set_str(serial_str, serial_short, sizeof(serial_str));
622                         printf("ID_SERIAL_SHORT=%s\n", serial_str);
623                         printf("ID_TYPE=%s\n", type_str);
624                 } else {
625                         if (reformat_serial)
626                                 format_serial(dev_scsi.serial);
627                         printf("%s\n", dev_scsi.serial);
628                 }
629                 dbg("%s\n", dev_scsi.serial);
630                 retval = 0;
631         }
632
633         return retval;
634 }
635
636 int main(int argc, char **argv)
637 {
638         int retval = 0;
639         char maj_min_dev[MAX_PATH_LEN];
640         int newargc;
641         char **newargv;
642
643         logging_init("scsi_id");
644         dbg("argc is %d\n", argc);
645
646         /*
647          * Get config file options.
648          */
649         newargv = NULL;
650         retval = get_file_options(NULL, NULL, &newargc, &newargv);
651         if (retval < 0) {
652                 retval = 1;
653                 goto exit;
654         }
655         if (newargv && (retval == 0)) {
656                 if (set_options(newargc, newargv, short_options, maj_min_dev) < 0) {
657                         retval = 2;
658                         goto exit;
659                 }
660                 free(newargv);
661         }
662
663         /*
664          * Get command line options (overriding any config file settings).
665          */
666         if (set_options(argc, argv, short_options, maj_min_dev) < 0)
667                 exit(1);
668
669         if (!dev_specified) {
670                 info("no device specified\n");
671                 retval = 1;
672                 goto exit;
673         }
674
675         retval = scsi_id(maj_min_dev);
676
677 exit:
678         logging_close();
679         return retval;
680 }