chiark / gitweb /
udev-builtin-blkid: modernizations and minor fixes
[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 <syslog.h>
29 #include <ctype.h>
30 #include <getopt.h>
31 #include <sys/stat.h>
32
33 #include "libudev.h"
34 #include "libudev-private.h"
35 #include "scsi_id.h"
36 #include "udev-util.h"
37
38 static const struct option options[] = {
39         { "device",             required_argument, NULL, 'd' },
40         { "config",             required_argument, NULL, 'f' },
41         { "page",               required_argument, NULL, 'p' },
42         { "blacklisted",        no_argument,       NULL, 'b' },
43         { "whitelisted",        no_argument,       NULL, 'g' },
44         { "replace-whitespace", no_argument,       NULL, 'u' },
45         { "sg-version",         required_argument, NULL, 's' },
46         { "verbose",            no_argument,       NULL, 'v' },
47         { "version",            no_argument,       NULL, 'V' }, /* don't advertise -V */
48         { "export",             no_argument,       NULL, 'x' },
49         { "help",               no_argument,       NULL, 'h' },
50         {}
51 };
52
53 static bool all_good = false;
54 static bool dev_specified = false;
55 static char config_file[MAX_PATH_LEN] = "/etc/scsi_id.config";
56 static enum page_code default_page_code = PAGE_UNSPECIFIED;
57 static int sg_version = 4;
58 static int debug = 0;
59 static bool reformat_serial = false;
60 static bool export = false;
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 _printf_(6,0)
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         const 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         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 const char *quote_string = "\"\n";
125         static const char *comma_string = ",\n";
126         char *val;
127         const 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         _cleanup_fclose_ FILE *f;
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         f = fopen(config_file, "re");
183         if (f == NULL) {
184                 if (errno == ENOENT)
185                         return 1;
186                 else {
187                         log_error("can't open %s: %m", config_file);
188                         return -1;
189                 }
190         }
191
192         /*
193          * Allocate a buffer rather than put it on the stack so we can
194          * keep it around to parse any options (any allocated newargv
195          * points into this buffer for its strings).
196          */
197         buffer = malloc(MAX_BUFFER_LEN);
198         if (!buffer)
199                 return log_oom();
200
201         *newargv = NULL;
202         lineno = 0;
203         while (1) {
204                 vendor_in = model_in = options_in = NULL;
205
206                 buf = fgets(buffer, MAX_BUFFER_LEN, f);
207                 if (buf == NULL)
208                         break;
209                 lineno++;
210                 if (buf[strlen(buffer) - 1] != '\n') {
211                         log_error("Config file line %d too long", lineno);
212                         break;
213                 }
214
215                 while (isspace(*buf))
216                         buf++;
217
218                 /* blank or all whitespace line */
219                 if (*buf == '\0')
220                         continue;
221
222                 /* comment line */
223                 if (*buf == '#')
224                         continue;
225
226                 str1 = strsep(&buf, "=");
227                 if (str1 && strcaseeq(str1, "VENDOR")) {
228                         str1 = get_value(&buf);
229                         if (!str1) {
230                                 retval = log_oom();
231                                 break;
232                         }
233                         vendor_in = str1;
234
235                         str1 = strsep(&buf, "=");
236                         if (str1 && strcaseeq(str1, "MODEL")) {
237                                 str1 = get_value(&buf);
238                                 if (!str1) {
239                                         retval = log_oom();
240                                         break;
241                                 }
242                                 model_in = str1;
243                                 str1 = strsep(&buf, "=");
244                         }
245                 }
246
247                 if (str1 && strcaseeq(str1, "OPTIONS")) {
248                         str1 = get_value(&buf);
249                         if (!str1) {
250                                 retval = log_oom();
251                                 break;
252                         }
253                         options_in = str1;
254                 }
255
256                 /*
257                  * Only allow: [vendor=foo[,model=bar]]options=stuff
258                  */
259                 if (!options_in || (!vendor_in && model_in)) {
260                         log_error("Error parsing config file line %d '%s'", lineno, buffer);
261                         retval = -1;
262                         break;
263                 }
264                 if (vendor == NULL) {
265                         if (vendor_in == NULL)
266                                 break;
267                 } else if (vendor_in &&
268                            strneq(vendor, vendor_in, strlen(vendor_in)) &&
269                            (!model_in ||
270                             (strneq(model, model_in, strlen(model_in))))) {
271                                 /*
272                                  * Matched vendor and optionally model.
273                                  *
274                                  * Note: a short vendor_in or model_in can
275                                  * give a partial match (that is FOO
276                                  * matches FOOBAR).
277                                  */
278                                 break;
279                 }
280         }
281
282         if (retval == 0) {
283                 if (vendor_in != NULL || model_in != NULL ||
284                     options_in != NULL) {
285                         /*
286                          * Something matched. Allocate newargv, and store
287                          * values found in options_in.
288                          */
289                         strcpy(buffer, options_in);
290                         c = argc_count(buffer) + 2;
291                         *newargv = calloc(c, sizeof(**newargv));
292                         if (!*newargv) {
293                                 retval = log_oom();
294                         } else {
295                                 *argc = c;
296                                 c = 0;
297                                 /*
298                                  * argv[0] at 0 is skipped by getopt, but
299                                  * store the buffer address there for
300                                  * later freeing
301                                  */
302                                 (*newargv)[c] = buffer;
303                                 for (c = 1; c < *argc; c++)
304                                         (*newargv)[c] = strsep(&buffer, " \t");
305                         }
306                 } else {
307                         /* No matches  */
308                         retval = 1;
309                 }
310         }
311         if (retval != 0)
312                 free(buffer);
313         return retval;
314 }
315
316 static void help(void) {
317         printf("Usage: scsi_id [OPTION...] DEVICE\n"
318                "  -d,--device=                     device node for SG_IO commands\n"
319                "  -f,--config=                     location of config file\n"
320                "  -p,--page=0x80|0x83|pre-spc3-83  SCSI page (0x80, 0x83, pre-spc3-83)\n"
321                "  -s,--sg-version=3|4              use SGv3 or SGv4\n"
322                "  -b,--blacklisted                 threat device as blacklisted\n"
323                "  -g,--whitelisted                 threat device as whitelisted\n"
324                "  -u,--replace-whitespace          replace all whitespace by underscores\n"
325                "  -v,--verbose                     verbose logging\n"
326                "     --version                     print version\n"
327                "  -x,--export                      print values as environment keys\n"
328                "  -h,--help                        print this help text\n\n");
329
330 }
331
332 static int set_options(struct udev *udev,
333                        int argc, char **argv,
334                        char *maj_min_dev)
335 {
336         int option;
337
338         /*
339          * optind is a global extern used by getopt. Since we can call
340          * set_options twice (once for command line, and once for config
341          * file) we have to reset this back to 1.
342          */
343         optind = 1;
344         while ((option = getopt_long(argc, argv, "d:f:gp:uvVxh", options, NULL)) >= 0)
345                 switch (option) {
346                 case 'b':
347                         all_good = false;
348                         break;
349
350                 case 'd':
351                         dev_specified = true;
352                         strscpy(maj_min_dev, MAX_PATH_LEN, optarg);
353                         break;
354
355                 case 'f':
356                         strscpy(config_file, MAX_PATH_LEN, optarg);
357                         break;
358
359                 case 'g':
360                         all_good = true;
361                         break;
362
363                 case 'h':
364                         help();
365                         exit(0);
366
367                 case 'p':
368                         if (streq(optarg, "0x80"))
369                                 default_page_code = PAGE_80;
370                         else if (streq(optarg, "0x83"))
371                                 default_page_code = PAGE_83;
372                         else if (streq(optarg, "pre-spc3-83"))
373                                 default_page_code = PAGE_83_PRE_SPC3;
374                         else {
375                                 log_error("Unknown page code '%s'", optarg);
376                                 return -1;
377                         }
378                         break;
379
380                 case 's':
381                         sg_version = atoi(optarg);
382                         if (sg_version < 3 || sg_version > 4) {
383                                 log_error("Unknown SG version '%s'", optarg);
384                                 return -1;
385                         }
386                         break;
387
388                 case 'u':
389                         reformat_serial = true;
390                         break;
391
392                 case 'v':
393                         debug++;
394                         break;
395
396                 case 'V':
397                         printf("%s\n", VERSION);
398                         exit(0);
399
400                 case 'x':
401                         export = true;
402                         break;
403
404                 case '?':
405                         return -1;
406
407                 default:
408                         assert_not_reached("Unknown option");
409                 }
410
411         if (optind < argc && !dev_specified) {
412                 dev_specified = true;
413                 strscpy(maj_min_dev, MAX_PATH_LEN, argv[optind]);
414         }
415
416         return 0;
417 }
418
419 static int per_dev_options(struct udev *udev,
420                            struct scsi_id_device *dev_scsi, int *good_bad, int *page_code)
421 {
422         int retval;
423         int newargc;
424         char **newargv = NULL;
425         int option;
426
427         *good_bad = all_good;
428         *page_code = default_page_code;
429
430         retval = get_file_options(udev, vendor_str, model_str, &newargc, &newargv);
431
432         optind = 1; /* reset this global extern */
433         while (retval == 0) {
434                 option = getopt_long(newargc, newargv, "bgp:", options, NULL);
435                 if (option == -1)
436                         break;
437
438                 switch (option) {
439                 case 'b':
440                         *good_bad = 0;
441                         break;
442
443                 case 'g':
444                         *good_bad = 1;
445                         break;
446
447                 case 'p':
448                         if (streq(optarg, "0x80")) {
449                                 *page_code = PAGE_80;
450                         } else if (streq(optarg, "0x83")) {
451                                 *page_code = PAGE_83;
452                         } else if (streq(optarg, "pre-spc3-83")) {
453                                 *page_code = PAGE_83_PRE_SPC3;
454                         } else {
455                                 log_error("Unknown page code '%s'", optarg);
456                                 retval = -1;
457                         }
458                         break;
459
460                 default:
461                         log_error("Unknown or bad option '%c' (0x%x)", option, option);
462                         retval = -1;
463                         break;
464                 }
465         }
466
467         if (newargv) {
468                 free(newargv[0]);
469                 free(newargv);
470         }
471         return retval;
472 }
473
474 static int set_inq_values(struct udev *udev, struct scsi_id_device *dev_scsi, const char *path)
475 {
476         int retval;
477
478         dev_scsi->use_sg = sg_version;
479
480         retval = scsi_std_inquiry(udev, dev_scsi, path);
481         if (retval)
482                 return retval;
483
484         udev_util_encode_string(dev_scsi->vendor, vendor_enc_str, sizeof(vendor_enc_str));
485         udev_util_encode_string(dev_scsi->model, model_enc_str, sizeof(model_enc_str));
486
487         util_replace_whitespace(dev_scsi->vendor, vendor_str, sizeof(vendor_str));
488         util_replace_chars(vendor_str, NULL);
489         util_replace_whitespace(dev_scsi->model, model_str, sizeof(model_str));
490         util_replace_chars(model_str, NULL);
491         set_type(dev_scsi->type, type_str, sizeof(type_str));
492         util_replace_whitespace(dev_scsi->revision, revision_str, sizeof(revision_str));
493         util_replace_chars(revision_str, NULL);
494         return 0;
495 }
496
497 /*
498  * scsi_id: try to get an id, if one is found, printf it to stdout.
499  * returns a value passed to exit() - 0 if printed an id, else 1.
500  */
501 static int scsi_id(struct udev *udev, char *maj_min_dev)
502 {
503         struct scsi_id_device dev_scsi = {};
504         int good_dev;
505         int page_code;
506         int retval = 0;
507
508         if (set_inq_values(udev, &dev_scsi, maj_min_dev) < 0) {
509                 retval = 1;
510                 goto out;
511         }
512
513         /* get per device (vendor + model) options from the config file */
514         per_dev_options(udev, &dev_scsi, &good_dev, &page_code);
515         if (!good_dev) {
516                 retval = 1;
517                 goto out;
518         }
519
520         /* read serial number from mode pages (no values for optical drives) */
521         scsi_get_serial(udev, &dev_scsi, maj_min_dev, page_code, MAX_SERIAL_LEN);
522
523         if (export) {
524                 char serial_str[MAX_SERIAL_LEN];
525
526                 printf("ID_SCSI=1\n");
527                 printf("ID_VENDOR=%s\n", vendor_str);
528                 printf("ID_VENDOR_ENC=%s\n", vendor_enc_str);
529                 printf("ID_MODEL=%s\n", model_str);
530                 printf("ID_MODEL_ENC=%s\n", model_enc_str);
531                 printf("ID_REVISION=%s\n", revision_str);
532                 printf("ID_TYPE=%s\n", type_str);
533                 if (dev_scsi.serial[0] != '\0') {
534                         util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
535                         util_replace_chars(serial_str, NULL);
536                         printf("ID_SERIAL=%s\n", serial_str);
537                         util_replace_whitespace(dev_scsi.serial_short, serial_str, sizeof(serial_str));
538                         util_replace_chars(serial_str, NULL);
539                         printf("ID_SERIAL_SHORT=%s\n", serial_str);
540                 }
541                 if (dev_scsi.wwn[0] != '\0') {
542                         printf("ID_WWN=0x%s\n", dev_scsi.wwn);
543                         if (dev_scsi.wwn_vendor_extension[0] != '\0') {
544                                 printf("ID_WWN_VENDOR_EXTENSION=0x%s\n", dev_scsi.wwn_vendor_extension);
545                                 printf("ID_WWN_WITH_EXTENSION=0x%s%s\n", dev_scsi.wwn, dev_scsi.wwn_vendor_extension);
546                         } else {
547                                 printf("ID_WWN_WITH_EXTENSION=0x%s\n", dev_scsi.wwn);
548                         }
549                 }
550                 if (dev_scsi.tgpt_group[0] != '\0') {
551                         printf("ID_TARGET_PORT=%s\n", dev_scsi.tgpt_group);
552                 }
553                 if (dev_scsi.unit_serial_number[0] != '\0') {
554                         printf("ID_SCSI_SERIAL=%s\n", dev_scsi.unit_serial_number);
555                 }
556                 goto out;
557         }
558
559         if (dev_scsi.serial[0] == '\0') {
560                 retval = 1;
561                 goto out;
562         }
563
564         if (reformat_serial) {
565                 char serial_str[MAX_SERIAL_LEN];
566
567                 util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
568                 util_replace_chars(serial_str, NULL);
569                 printf("%s\n", serial_str);
570                 goto out;
571         }
572
573         printf("%s\n", dev_scsi.serial);
574 out:
575         return retval;
576 }
577
578 int main(int argc, char **argv)
579 {
580         _cleanup_udev_unref_ struct udev *udev;
581         int retval = 0;
582         char maj_min_dev[MAX_PATH_LEN];
583         int newargc;
584         char **newargv = NULL;
585
586         udev = udev_new();
587         if (udev == NULL)
588                 goto exit;
589
590         log_open();
591         udev_set_log_fn(udev, log_fn);
592
593         /*
594          * Get config file options.
595          */
596         retval = get_file_options(udev, NULL, NULL, &newargc, &newargv);
597         if (retval < 0) {
598                 retval = 1;
599                 goto exit;
600         }
601         if (retval == 0) {
602                 assert(newargv);
603
604                 if (set_options(udev, newargc, newargv, maj_min_dev) < 0) {
605                         retval = 2;
606                         goto exit;
607                 }
608         }
609
610         /*
611          * Get command line options (overriding any config file settings).
612          */
613         if (set_options(udev, argc, argv, maj_min_dev) < 0)
614                 exit(1);
615
616         if (!dev_specified) {
617                 log_error("no device specified");
618                 retval = 1;
619                 goto exit;
620         }
621
622         retval = scsi_id(udev, maj_min_dev);
623
624 exit:
625         if (newargv) {
626                 free(newargv[0]);
627                 free(newargv);
628         }
629         log_close();
630         return retval;
631 }