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