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