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