chiark / gitweb /
udev: switch to systemd logging functions
[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("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: scsi_id [OPTION...] DEVICE\n"
308                "  -d,--device=                     device node for SG_IO commands\n"
309                "  -f,--config=                     location of config file\n"
310                "  -p,--page=0x80|0x83|pre-spc3-83  SCSI page (0x80, 0x83, pre-spc3-83)\n"
311                "  -s,--sg-version=3|4              use SGv3 or SGv4\n"
312                "  -b,--blacklisted                 treat device as blacklisted\n"
313                "  -g,--whitelisted                 treat device as whitelisted\n"
314                "  -u,--replace-whitespace          replace all whitespace by underscores\n"
315                "  -v,--verbose                     verbose logging\n"
316                "     --version                     print version\n"
317                "  -x,--export                      print values as environment keys\n"
318                "  -h,--help                        print this help text\n\n");
319
320 }
321
322 static int set_options(struct udev *udev,
323                        int argc, char **argv,
324                        char *maj_min_dev)
325 {
326         int option;
327
328         /*
329          * optind is a global extern used by getopt. Since we can call
330          * set_options twice (once for command line, and once for config
331          * file) we have to reset this back to 1.
332          */
333         optind = 1;
334         while ((option = getopt_long(argc, argv, "d:f:gp:uvVxh", options, NULL)) >= 0)
335                 switch (option) {
336                 case 'b':
337                         all_good = false;
338                         break;
339
340                 case 'd':
341                         dev_specified = true;
342                         strscpy(maj_min_dev, MAX_PATH_LEN, optarg);
343                         break;
344
345                 case 'f':
346                         strscpy(config_file, MAX_PATH_LEN, optarg);
347                         break;
348
349                 case 'g':
350                         all_good = true;
351                         break;
352
353                 case 'h':
354                         help();
355                         exit(0);
356
357                 case 'p':
358                         if (streq(optarg, "0x80"))
359                                 default_page_code = PAGE_80;
360                         else if (streq(optarg, "0x83"))
361                                 default_page_code = PAGE_83;
362                         else if (streq(optarg, "pre-spc3-83"))
363                                 default_page_code = PAGE_83_PRE_SPC3;
364                         else {
365                                 log_error("Unknown page code '%s'", optarg);
366                                 return -1;
367                         }
368                         break;
369
370                 case 's':
371                         sg_version = atoi(optarg);
372                         if (sg_version < 3 || sg_version > 4) {
373                                 log_error("Unknown SG version '%s'", optarg);
374                                 return -1;
375                         }
376                         break;
377
378                 case 'u':
379                         reformat_serial = true;
380                         break;
381
382                 case 'v':
383                         log_set_target(LOG_TARGET_CONSOLE);
384                         log_set_max_level(LOG_DEBUG);
385                         log_open();
386                         break;
387
388                 case 'V':
389                         printf("%s\n", VERSION);
390                         exit(0);
391
392                 case 'x':
393                         export = true;
394                         break;
395
396                 case '?':
397                         return -1;
398
399                 default:
400                         assert_not_reached("Unknown option");
401                 }
402
403         if (optind < argc && !dev_specified) {
404                 dev_specified = true;
405                 strscpy(maj_min_dev, MAX_PATH_LEN, argv[optind]);
406         }
407
408         return 0;
409 }
410
411 static int per_dev_options(struct udev *udev,
412                            struct scsi_id_device *dev_scsi, int *good_bad, int *page_code)
413 {
414         int retval;
415         int newargc;
416         char **newargv = NULL;
417         int option;
418
419         *good_bad = all_good;
420         *page_code = default_page_code;
421
422         retval = get_file_options(udev, vendor_str, model_str, &newargc, &newargv);
423
424         optind = 1; /* reset this global extern */
425         while (retval == 0) {
426                 option = getopt_long(newargc, newargv, "bgp:", options, NULL);
427                 if (option == -1)
428                         break;
429
430                 switch (option) {
431                 case 'b':
432                         *good_bad = 0;
433                         break;
434
435                 case 'g':
436                         *good_bad = 1;
437                         break;
438
439                 case 'p':
440                         if (streq(optarg, "0x80")) {
441                                 *page_code = PAGE_80;
442                         } else if (streq(optarg, "0x83")) {
443                                 *page_code = PAGE_83;
444                         } else if (streq(optarg, "pre-spc3-83")) {
445                                 *page_code = PAGE_83_PRE_SPC3;
446                         } else {
447                                 log_error("Unknown page code '%s'", optarg);
448                                 retval = -1;
449                         }
450                         break;
451
452                 default:
453                         log_error("Unknown or bad option '%c' (0x%x)", option, option);
454                         retval = -1;
455                         break;
456                 }
457         }
458
459         if (newargv) {
460                 free(newargv[0]);
461                 free(newargv);
462         }
463         return retval;
464 }
465
466 static int set_inq_values(struct udev *udev, struct scsi_id_device *dev_scsi, const char *path)
467 {
468         int retval;
469
470         dev_scsi->use_sg = sg_version;
471
472         retval = scsi_std_inquiry(udev, dev_scsi, path);
473         if (retval)
474                 return retval;
475
476         udev_util_encode_string(dev_scsi->vendor, vendor_enc_str, sizeof(vendor_enc_str));
477         udev_util_encode_string(dev_scsi->model, model_enc_str, sizeof(model_enc_str));
478
479         util_replace_whitespace(dev_scsi->vendor, vendor_str, sizeof(vendor_str));
480         util_replace_chars(vendor_str, NULL);
481         util_replace_whitespace(dev_scsi->model, model_str, sizeof(model_str));
482         util_replace_chars(model_str, NULL);
483         set_type(dev_scsi->type, type_str, sizeof(type_str));
484         util_replace_whitespace(dev_scsi->revision, revision_str, sizeof(revision_str));
485         util_replace_chars(revision_str, NULL);
486         return 0;
487 }
488
489 /*
490  * scsi_id: try to get an id, if one is found, printf it to stdout.
491  * returns a value passed to exit() - 0 if printed an id, else 1.
492  */
493 static int scsi_id(struct udev *udev, char *maj_min_dev)
494 {
495         struct scsi_id_device dev_scsi = {};
496         int good_dev;
497         int page_code;
498         int retval = 0;
499
500         if (set_inq_values(udev, &dev_scsi, maj_min_dev) < 0) {
501                 retval = 1;
502                 goto out;
503         }
504
505         /* get per device (vendor + model) options from the config file */
506         per_dev_options(udev, &dev_scsi, &good_dev, &page_code);
507         if (!good_dev) {
508                 retval = 1;
509                 goto out;
510         }
511
512         /* read serial number from mode pages (no values for optical drives) */
513         scsi_get_serial(udev, &dev_scsi, maj_min_dev, page_code, MAX_SERIAL_LEN);
514
515         if (export) {
516                 char serial_str[MAX_SERIAL_LEN];
517
518                 printf("ID_SCSI=1\n");
519                 printf("ID_VENDOR=%s\n", vendor_str);
520                 printf("ID_VENDOR_ENC=%s\n", vendor_enc_str);
521                 printf("ID_MODEL=%s\n", model_str);
522                 printf("ID_MODEL_ENC=%s\n", model_enc_str);
523                 printf("ID_REVISION=%s\n", revision_str);
524                 printf("ID_TYPE=%s\n", type_str);
525                 if (dev_scsi.serial[0] != '\0') {
526                         util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
527                         util_replace_chars(serial_str, NULL);
528                         printf("ID_SERIAL=%s\n", serial_str);
529                         util_replace_whitespace(dev_scsi.serial_short, serial_str, sizeof(serial_str));
530                         util_replace_chars(serial_str, NULL);
531                         printf("ID_SERIAL_SHORT=%s\n", serial_str);
532                 }
533                 if (dev_scsi.wwn[0] != '\0') {
534                         printf("ID_WWN=0x%s\n", dev_scsi.wwn);
535                         if (dev_scsi.wwn_vendor_extension[0] != '\0') {
536                                 printf("ID_WWN_VENDOR_EXTENSION=0x%s\n", dev_scsi.wwn_vendor_extension);
537                                 printf("ID_WWN_WITH_EXTENSION=0x%s%s\n", dev_scsi.wwn, dev_scsi.wwn_vendor_extension);
538                         } else {
539                                 printf("ID_WWN_WITH_EXTENSION=0x%s\n", dev_scsi.wwn);
540                         }
541                 }
542                 if (dev_scsi.tgpt_group[0] != '\0') {
543                         printf("ID_TARGET_PORT=%s\n", dev_scsi.tgpt_group);
544                 }
545                 if (dev_scsi.unit_serial_number[0] != '\0') {
546                         printf("ID_SCSI_SERIAL=%s\n", dev_scsi.unit_serial_number);
547                 }
548                 goto out;
549         }
550
551         if (dev_scsi.serial[0] == '\0') {
552                 retval = 1;
553                 goto out;
554         }
555
556         if (reformat_serial) {
557                 char serial_str[MAX_SERIAL_LEN];
558
559                 util_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str));
560                 util_replace_chars(serial_str, NULL);
561                 printf("%s\n", serial_str);
562                 goto out;
563         }
564
565         printf("%s\n", dev_scsi.serial);
566 out:
567         return retval;
568 }
569
570 int main(int argc, char **argv)
571 {
572         _cleanup_udev_unref_ struct udev *udev;
573         int retval = 0;
574         char maj_min_dev[MAX_PATH_LEN];
575         int newargc;
576         char **newargv = NULL;
577
578         log_parse_environment();
579         log_open();
580
581         udev = udev_new();
582         if (udev == NULL)
583                 goto exit;
584
585         /*
586          * Get config file options.
587          */
588         retval = get_file_options(udev, NULL, NULL, &newargc, &newargv);
589         if (retval < 0) {
590                 retval = 1;
591                 goto exit;
592         }
593         if (retval == 0) {
594                 assert(newargv);
595
596                 if (set_options(udev, newargc, newargv, maj_min_dev) < 0) {
597                         retval = 2;
598                         goto exit;
599                 }
600         }
601
602         /*
603          * Get command line options (overriding any config file settings).
604          */
605         if (set_options(udev, argc, argv, maj_min_dev) < 0)
606                 exit(1);
607
608         if (!dev_specified) {
609                 log_error("no device specified");
610                 retval = 1;
611                 goto exit;
612         }
613
614         retval = scsi_id(udev, maj_min_dev);
615
616 exit:
617         if (newargv) {
618                 free(newargv[0]);
619                 free(newargv);
620         }
621         log_close();
622         return retval;
623 }