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