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