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