Debian Codegraph @

src/udev/scsi_id/scsi_id.c

raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3 * Copyright © IBM Corp. 2003
4 * Copyright © SUSE Linux Products GmbH, 2006
5 */
6
7 #include <ctype.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 #include "alloc-util.h"
12 #include "build.h"
13 #include "device-nodes.h"
14 #include "extract-word.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "format-table.h"
18 #include "help-util.h"
19 #include "main-func.h"
20 #include "options.h"
21 #include "parse-util.h"
22 #include "scsi_id.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "strxcpyx.h"
26 #include "udev-util.h"
27 #include "utf8.h"
28
29 static bool all_good = false;
30 static bool dev_specified = false;
31 static char config_file[MAX_PATH_LEN] = "/etc/scsi_id.config";
32 static enum page_code default_page_code = PAGE_UNSPECIFIED;
33 static int sg_version = 4;
34 static bool reformat_serial = false;
35 static bool export = false;
36 static char vendor_str[64];
37 static char model_str[64];
38 static char vendor_enc_str[256];
39 static char model_enc_str[256];
40 static char revision_str[16];
41 static char type_str[16];
42
43 static void set_type(unsigned type_num, char *to, size_t len) {
44 const char *type;
45
46 switch (type_num) {
47 case 0:
48 type = "disk";
49 break;
50 case 1:
51 type = "tape";
52 break;
53 case 4:
54 type = "optical";
55 break;
56 case 5:
57 type = "cd";
58 break;
59 case 7:
60 type = "optical";
61 break;
62 case 0xe:
63 type = "disk";
64 break;
65 case 0xf:
66 type = "optical";
67 break;
68 case 0x14:
69 /*
70 * Use "zbc" here to be brief and consistent with "lsscsi" command.
71 * Other tools, e.g., "sg3_utils" would say "host managed zoned block".
72 */
73 type = "zbc";
74 break;
75 default:
76 type = "generic";
77 }
78 strscpy(to, len, type);
79 }
80
81 /*
82 * get_file_options:
83 *
84 * If vendor == NULL, find a line in the config file with only "OPTIONS=";
85 * if vendor and model are set find the first OPTIONS line in the config
86 * file that matches. Set argc and argv to match the OPTIONS string.
87 *
88 * vendor and model can end in '\n'.
89 */
90 static int get_file_options(const char *vendor, const char *model, char ***ret_argv) {
91 _cleanup_free_ char *vendor_in = NULL, *model_in = NULL, *options_in = NULL; /* read in from file */
92 _cleanup_strv_free_ char **options_argv = NULL;
93 int r;
94
95 _cleanup_fclose_ FILE *f = fopen(config_file, "re");
96 if (!f) {
97 if (errno == ENOENT)
98 goto finish;
99 return log_error_errno(errno, "Cannot open %s: %m", config_file);
100 }
101
102 for (int lineno = 0;;) {
103 _cleanup_free_ char *buffer = NULL, *key = NULL, *value = NULL;
104 const char *buf;
105
106 r = read_line(f, MAX_BUFFER_LEN, &buffer);
107 if (r < 0)
108 return log_error_errno(r, "read_line() on line %d of %s failed: %m", lineno, config_file);
109 if (r == 0)
110 break;
111 buf = buffer;
112 lineno++;
113
114 while (isspace(*buf))
115 buf++;
116
117 /* blank or all whitespace line */
118 if (*buf == '\0')
119 continue;
120
121 /* comment line */
122 if (*buf == '#')
123 continue;
124
125 r = extract_many_words(&buf, "=\",\n", 0, &key, &value);
126 if (r < 2)
127 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Error parsing config file line %d '%s'", lineno, buffer);
128
129 if (strcaseeq(key, "VENDOR")) {
130 vendor_in = TAKE_PTR(value);
131
132 key = mfree(key);
133 r = extract_many_words(&buf, "=\",\n", 0, &key, &value);
134 if (r < 2)
135 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Error parsing config file line %d '%s'", lineno, buffer);
136
137 if (strcaseeq(key, "MODEL")) {
138 model_in = TAKE_PTR(value);
139
140 key = mfree(key);
141 r = extract_many_words(&buf, "=\",\n", 0, &key, &value);
142 if (r < 2)
143 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Error parsing config file line %d '%s'", lineno, buffer);
144 }
145 }
146
147 if (strcaseeq(key, "OPTIONS"))
148 options_in = TAKE_PTR(value);
149
150 /*
151 * Only allow: [vendor=foo[,model=bar]]options=stuff
152 */
153 if (!options_in || (!vendor_in && model_in))
154 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Error parsing config file line %d '%s'", lineno, buffer);
155 if (!vendor) {
156 if (!vendor_in)
157 break;
158 } else if (vendor_in &&
159 startswith(vendor, vendor_in) &&
160 (!model_in || startswith(model, model_in))) {
161 /*
162 * Matched vendor and optionally model.
163 *
164 * Note: a short vendor_in or model_in can
165 * give a partial match (that is FOO
166 * matches FOOBAR).
167 */
168 break;
169 }
170
171 vendor_in = mfree(vendor_in);
172 model_in = mfree(model_in);
173 options_in = mfree(options_in);
174
175 }
176
177 if (!vendor_in && !model_in && !options_in)
178 goto finish; /* No matches */
179
180 /* Something matched. Allocate newargv, and store values found in options_in. */
181 options_argv = strv_split(options_in, " \t");
182 if (!options_argv)
183 return log_oom();
184 r = strv_prepend(&options_argv, ""); /* argv[0] is skipped */
185 if (r < 0)
186 return r;
187
188 finish:
189 *ret_argv = TAKE_PTR(options_argv);
190 return !!*ret_argv; /* true if something matched, false otherwise */
191 }
192
193 static int parse_page_code(const char *value, enum page_code *ret) {
194 assert(value);
195 assert(ret);
196
197 if (streq(value, "0x80"))
198 *ret = PAGE_80;
199 else if (streq(value, "0x83"))
200 *ret = PAGE_83;
201 else if (streq(value, "pre-spc3-83"))
202 *ret = PAGE_83_PRE_SPC3;
203 else
204 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
205 "Unknown page code '%s'", value);
206 return 0;
207 }
208
209 static int help(void) {
210 _cleanup_(table_unrefp) Table *options = NULL;
211 int r;
212
213 r = option_parser_get_help_table(&options);
214 if (r < 0)
215 return r;
216
217 help_cmdline("[OPTION...] DEVICE");
218 help_abstract("SCSI device identification.");
219 help_section("Options");
220
221 return table_print_or_warn(options);
222 }
223
224 static int set_options(int argc, char **argv, char *maj_min_dev) {
225 assert(argc >= 0);
226 assert(argv);
227
228 OptionParser opts = { argc, argv };
229 int r;
230
231 FOREACH_OPTION_OR_RETURN(c, &opts)
232 switch (c) {
233
234 OPTION_COMMON_HELP:
235 return help();
236
237 OPTION_COMMON_VERSION_WITH_HIDDEN_V:
238 return version();
239
240 OPTION('d', "device", "PATH", "Device node for SG_IO commands"):
241 dev_specified = true;
242 strscpy(maj_min_dev, MAX_PATH_LEN, opts.arg);
243 break;
244
245 OPTION('f', "config", "PATH", "Location of config file"):
246 strscpy(config_file, MAX_PATH_LEN, opts.arg);
247 break;
248
249 OPTION('p', "page", "0x80|0x83|pre-spc3-83", "SCSI page"):
250 r = parse_page_code(opts.arg, &default_page_code);
251 if (r < 0)
252 return r;
253 break;
254
255 OPTION('s', "sg-version", "3|4", "Use SGv3 or SGv4"):
256 r = safe_atoi(opts.arg, &sg_version);
257 if (r < 0)
258 return log_error_errno(r, "Invalid SG version '%s'", opts.arg);
259 if (!IN_SET(sg_version, 3, 4))
260 return log_error_errno(SYNTHETIC_ERRNO(ERANGE),
261 "Unknown SG version '%s'", opts.arg);
262 break;
263
264 OPTION('b', "denylisted", NULL, "Treat device as denylisted"): {}
265 OPTION('b', "blacklisted", NULL, /* help= */ NULL): /* backward compat */
266 all_good = false;
267 break;
268
269 OPTION('g', "allowlisted", NULL, "Treat device as allowlisted"): {}
270 OPTION('g', "whitelisted", NULL, /* help= */ NULL): /* backward compat */
271 all_good = true;
272 break;
273
274 OPTION('u', "replace-whitespace", NULL, "Replace all whitespace by underscores"):
275 reformat_serial = true;
276 break;
277
278 OPTION('v', "verbose", NULL, "Verbose logging"):
279 log_set_target(LOG_TARGET_CONSOLE);
280 log_set_max_level(LOG_DEBUG);
281 log_open();
282 break;
283
284 OPTION('x', "export", NULL, "Print values as environment keys"):
285 export = true;
286 break;
287 }
288
289 char **args = option_parser_get_args(&opts);
290 if (!strv_isempty(args) && !dev_specified) {
291 dev_specified = true;
292 strscpy(maj_min_dev, MAX_PATH_LEN, args[0]);
293 }
294
295 return 1;
296 }
297
298 static int per_dev_options(struct scsi_id_device *dev_scsi, int *good_bad, enum page_code *page_code) {
299 int r;
300
301 assert(dev_scsi);
302 assert(good_bad);
303 assert(page_code);
304
305 *good_bad = all_good;
306 *page_code = default_page_code;
307
308 _cleanup_strv_free_ char **newargv = NULL;
309 r = get_file_options(vendor_str, model_str, &newargv);
310 if (r <= 0)
311 return r;
312
313 size_t newargc = strv_length(newargv);
314 if (newargc > INT_MAX)
315 return log_oom(); /* Close enough :) */
316
317 OptionParser opts = { newargc, newargv };
318
319 /* We reuse the option parser, but only a subset of the options is supported here.
320 * If any others are encountered, return an error. */
321
322 FOREACH_OPTION_OR_RETURN(c, &opts)
323 if (opts.opt->short_code == 'b')
324 *good_bad = 0;
325 else if (opts.opt->short_code == 'g')
326 *good_bad = 1;
327 else if (opts.opt->short_code == 'p') {
328 r = parse_page_code(opts.arg, page_code);
329 if (r < 0)
330 return r;
331 } else {
332 _cleanup_free_ char *synopsis =
333 option_get_synopsis(opts.opt, "/", /* show_metavar=*/ false);
334 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
335 "Option %s not supported in the config file.",
336 strnull(synopsis));
337 }
338
339 return 0;
340 }
341
342 static int set_inq_values(struct scsi_id_device *dev_scsi, const char *path) {
343 int r;
344
345 dev_scsi->use_sg = sg_version;
346
347 r = scsi_std_inquiry(dev_scsi, path);
348 if (r < 0)
349 return r;
350
351 encode_devnode_name(dev_scsi->vendor, vendor_enc_str, sizeof(vendor_enc_str));
352 encode_devnode_name(dev_scsi->model, model_enc_str, sizeof(model_enc_str));
353
354 udev_replace_whitespace(dev_scsi->vendor, vendor_str, sizeof(vendor_str)-1);
355 udev_replace_chars(vendor_str, NULL);
356 udev_replace_whitespace(dev_scsi->model, model_str, sizeof(model_str)-1);
357 udev_replace_chars(model_str, NULL);
358 set_type(dev_scsi->type, type_str, sizeof(type_str));
359 udev_replace_whitespace(dev_scsi->revision, revision_str, sizeof(revision_str)-1);
360 udev_replace_chars(revision_str, NULL);
361 return 0;
362 }
363
364 static bool scsi_string_is_valid(const char *s) {
365 return !isempty(s) && utf8_is_valid(s) && !string_has_cc(s, /* ok= */ NULL);
366 }
367
368 /*
369 * scsi_id: try to get an id, if one is found, printf it to stdout.
370 */
371 static int scsi_id(char *maj_min_dev) {
372 struct scsi_id_device dev_scsi = {};
373 enum page_code page_code;
374 int good_dev, r;
375
376 r = set_inq_values(&dev_scsi, maj_min_dev);
377 if (r < 0)
378 return r;
379
380 /* get per device (vendor + model) options from the config file */
381 r = per_dev_options(&dev_scsi, &good_dev, &page_code);
382 if (r < 0)
383 return r;
384 if (!good_dev)
385 return -EIO;
386
387 /* read serial number from mode pages (no values for optical drives) */
388 (void) scsi_get_serial(&dev_scsi, maj_min_dev, page_code, MAX_SERIAL_LEN);
389
390 if (export) {
391 char serial_str[MAX_SERIAL_LEN];
392
393 printf("ID_SCSI=1\n");
394 printf("ID_VENDOR=%s\n", vendor_str);
395 printf("ID_VENDOR_ENC=%s\n", vendor_enc_str);
396 printf("ID_MODEL=%s\n", model_str);
397 printf("ID_MODEL_ENC=%s\n", model_enc_str);
398 printf("ID_REVISION=%s\n", revision_str);
399 printf("ID_TYPE=%s\n", type_str);
400 if (dev_scsi.serial[0] != '\0') {
401 udev_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str)-1);
402 udev_replace_chars(serial_str, NULL);
403 printf("ID_SERIAL=%s\n", serial_str);
404 udev_replace_whitespace(dev_scsi.serial_short, serial_str, sizeof(serial_str)-1);
405 udev_replace_chars(serial_str, NULL);
406 printf("ID_SERIAL_SHORT=%s\n", serial_str);
407 }
408 if (scsi_string_is_valid(dev_scsi.wwn)) {
409 printf("ID_WWN=0x%s\n", dev_scsi.wwn);
410 if (scsi_string_is_valid(dev_scsi.wwn_vendor_extension)) {
411 printf("ID_WWN_VENDOR_EXTENSION=0x%s\n", dev_scsi.wwn_vendor_extension);
412 printf("ID_WWN_WITH_EXTENSION=0x%s%s\n", dev_scsi.wwn, dev_scsi.wwn_vendor_extension);
413 } else
414 printf("ID_WWN_WITH_EXTENSION=0x%s\n", dev_scsi.wwn);
415 }
416 if (scsi_string_is_valid(dev_scsi.tgpt_group))
417 printf("ID_TARGET_PORT=%s\n", dev_scsi.tgpt_group);
418 if (scsi_string_is_valid(dev_scsi.unit_serial_number))
419 printf("ID_SCSI_SERIAL=%s\n", dev_scsi.unit_serial_number);
420 return 0;
421 }
422
423 if (dev_scsi.serial[0] == '\0')
424 return -ENODATA;
425
426 if (reformat_serial) {
427 char serial_str[MAX_SERIAL_LEN];
428
429 udev_replace_whitespace(dev_scsi.serial, serial_str, sizeof(serial_str)-1);
430 udev_replace_chars(serial_str, NULL);
431 printf("%s\n", serial_str);
432 return 0;
433 }
434
435 printf("%s\n", dev_scsi.serial);
436 return 0;
437 }
438
439 static int run(int argc, char **argv) {
440 _cleanup_strv_free_ char **newargv = NULL;
441 char maj_min_dev[MAX_PATH_LEN];
442 int r;
443
444 (void) udev_parse_config();
445 log_setup();
446
447 /*
448 * Get config file options.
449 */
450 r = get_file_options(NULL, NULL, &newargv);
451 if (r < 0)
452 return r;
453 if (r == 1) {
454 size_t newargc = strv_length(newargv);
455 if (newargc > INT_MAX)
456 return log_oom(); /* Close enough :) */
457
458 r = set_options(newargc, newargv, maj_min_dev);
459 if (r <= 0)
460 return r;
461 }
462
463 /*
464 * Get command line options (overriding any config file settings).
465 */
466 r = set_options(argc, argv, maj_min_dev);
467 if (r <= 0)
468 return r;
469
470 if (!dev_specified)
471 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No device specified.");
472
473 return scsi_id(maj_min_dev);
474 }
475
476 DEFINE_MAIN_FUNCTION(run);