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