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