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