chiark / gitweb /
[PATCH] update udev scsi_id to scsi_id 0.4
[elogind.git] / extras / scsi_id / scsi_id.c
1 /*
2  * scsi_id.c
3  *
4  * Main section of the scsi_id program
5  *
6  * Copyright (C) IBM Corp. 2003
7  *
8  *  This library is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU Lesser General Public License as
10  *  published by the Free Software Foundation; either version 2.1 of the
11  *  License, or (at your option) any later version.
12  *
13  *  This library is distributed in the hope that it will be useful, but
14  *  WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with this library; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21  *  USA
22  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <syslog.h>
32 #include <stdarg.h>
33 #include <ctype.h>
34 #include <sys/stat.h>
35 #include <sysfs/libsysfs.h>
36 #include "scsi_id_version.h"
37 #include "scsi_id.h"
38
39 #ifndef SCSI_ID_VERSION
40 #warning No version
41 #define SCSI_ID_VERSION "unknown"
42 #endif
43
44 /*
45  * temporary names for mknod.
46  */
47 #define TMP_DIR "/tmp"
48 #define TMP_PREFIX "scsi"
49
50 /*
51  * XXX Note the 'e' (send output to stderr in all cases), and 'c' (callout)
52  * options are not supported, but other code is still left in place for
53  * now.
54  */
55 static const char short_options[] = "bd:f:gip:s:vV";
56 /*
57  * Just duplicate per dev options.
58  */
59 static const char dev_short_options[] = "bgp:";
60
61 char sysfs_mnt_path[SYSFS_PATH_MAX];
62
63 static int all_good;
64 static char *default_callout;
65 static int dev_specified;
66 static int sys_specified;
67 static char config_file[MAX_NAME_LEN] = SCSI_ID_CONFIG_FILE;
68 static int display_bus_id;
69 static int default_page_code;
70 static int use_stderr;
71 static int debug;
72 static int hotplug_mode;
73
74 void log_message (int level, const char *format, ...)
75 {
76         va_list args;
77
78         if (!debug && level == LOG_DEBUG)
79                 return;
80
81         va_start (args, format);
82         if (!hotplug_mode || use_stderr) {
83                 vfprintf(stderr, format, args);
84         } else {
85                 static int logging_init = 0;
86                 static unsigned char logname[32];
87                 if (!logging_init) {
88                         /*
89                          * klibc does not have LOG_PID.
90                          */
91                         snprintf(logname, 32, "scsi_id[%d]", getpid());
92                         openlog (logname, 0, LOG_DAEMON);
93                         logging_init = 1;
94                 }
95
96                 vsyslog(level, format, args);
97         }
98         va_end (args);
99         return;
100 }
101
102 int sysfs_get_attr(const char *devpath, const char *attr, char *value,
103                    size_t bufsize)
104 {
105         char attr_path[SYSFS_PATH_MAX];
106
107         strncpy(attr_path, devpath, SYSFS_PATH_MAX);
108         strncat(attr_path, "/", SYSFS_PATH_MAX);
109         strncat(attr_path, attr,  SYSFS_PATH_MAX);
110         dprintf("%s\n", attr_path);
111         return sysfs_read_attribute_value(attr_path, value, SYSFS_NAME_LEN);
112 }
113
114 static int get_major_minor(const char *devpath, int *major, int *minor)
115 {
116         char dev_value[MAX_ATTR_LEN];
117
118         if (sysfs_get_attr(devpath, "dev", dev_value, MAX_ATTR_LEN)) {
119                 /*
120                  * XXX This happens a lot, since sg has no dev attr.
121                  * And now sysfsutils does not set a meaningful errno
122                  * value. Someday change this back to a LOG_WARNING.
123                  * And if sysfsutils changes, check for ENOENT and handle
124                  * it separately.
125                  */
126                 log_message(LOG_DEBUG, "%s: could not get dev attribute: %s\n",
127                         devpath, strerror(errno));
128                 return -1;
129         }
130
131         dprintf("dev value %s", dev_value); /* dev_value has a trailing \n */
132         if (sscanf(dev_value, "%u:%u", major, minor) != 2) {
133                 log_message(LOG_WARNING, "%s: invalid dev major/minor\n",
134                             devpath);
135                 return -1;
136         }
137
138         return 0;
139 }
140
141 static int create_tmp_dev(const char *devpath, char *tmpdev, int dev_type)
142 {
143         int major, minor;
144
145         dprintf("(%s)\n", devpath);
146
147         if (get_major_minor(devpath, &major, &minor))
148                 return -1;
149         snprintf(tmpdev, MAX_NAME_LEN, "%s/%s-maj%d-min%d-%u",
150                  TMP_DIR, TMP_PREFIX, major, minor, getpid());
151
152         dprintf("tmpdev '%s'\n", tmpdev);
153
154         if (mknod(tmpdev, 0600 | dev_type, makedev(major, minor))) {
155                 log_message(LOG_WARNING, "mknod failed: %s\n", strerror(errno));
156                 return -1;
157         }
158         return 0;
159 }
160
161 static int has_sysfs_prefix(const char *path, const char *prefix)
162 {
163         char match[MAX_NAME_LEN];
164
165         strncpy(match, sysfs_mnt_path, MAX_NAME_LEN);
166         strncat(match, prefix, MAX_NAME_LEN);
167         if (strncmp(path, match, strlen(match)) == 0)
168                 return 1;
169         else
170                 return 0;
171 }
172
173 /*
174  * get_value:
175  *
176  * buf points to an '=' followed by a quoted string ("foo") or a string ending
177  * with a space or ','.
178  *
179  * Return a pointer to the NUL terminated string, returns NULL if no
180  * matches.
181  */
182 static char *get_value(char **buffer)
183 {
184         static char *quote_string = "\"\n";
185         static char *comma_string = ",\n";
186         char *val;
187         char *end;
188
189         if (**buffer == '"') {
190                 /*
191                  * skip leading quote, terminate when quote seen
192                  */
193                 (*buffer)++;
194                 end = quote_string;
195         } else {
196                 end = comma_string;
197         }
198         val = strsep(buffer, end);
199         if (val && end == quote_string)
200                 /*
201                  * skip trailing quote
202                  */
203                 (*buffer)++;
204
205         while (isspace(**buffer))
206                 (*buffer)++;
207
208         return val;
209 }
210
211 static int argc_count(char *opts)
212 {
213         int i = 0;
214         while (*opts != '\0')
215                 if (*opts++ == ' ')
216                         i++;
217         return i;
218 }
219
220 /*
221  * get_file_options:
222  *
223  * If vendor == NULL, find a line in the config file with only "OPTIONS=";
224  * if vendor and model are set find the first OPTIONS line in the config
225  * file that matches. Set argc and argv to match the OPTIONS string.
226  *
227  * vendor and model can end in '\n'.
228  */
229 static int get_file_options(char *vendor, char *model, int *argc,
230                             char ***newargv)
231 {
232         char *buffer;
233         FILE *fd;
234         char *buf;
235         char *str1;
236         char *vendor_in, *model_in, *options_in; /* read in from file */
237         int lineno;
238         int c;
239         int retval = 0;
240
241         dprintf("vendor='%s'; model='%s'\n", vendor, model);
242         fd = fopen(config_file, "r");
243         if (fd == NULL) {
244                 dprintf("can't open %s\n", config_file);
245                 if (errno == ENOENT) {
246                         return 1;
247                 } else {
248                         log_message(LOG_WARNING, "can't open %s: %s\n",
249                                 config_file, strerror(errno));
250                         return -1;
251                 }
252         }
253
254         /*
255          * Allocate a buffer rather than put it on the stack so we can
256          * keep it around to parse any options (any allocated newargv
257          * points into this buffer for its strings).
258          */
259         buffer = malloc(MAX_BUFFER_LEN);
260         if (!buffer) {
261                 log_message(LOG_WARNING, "Can't allocate memory.\n");
262                 return -1;
263         }
264
265         *newargv = NULL;
266         lineno = 0;
267         while (1) {
268                 vendor_in = model_in = options_in = NULL;
269
270                 buf = fgets(buffer, MAX_BUFFER_LEN, fd);
271                 if (buf == NULL)
272                         break;
273                 lineno++;
274                 if (buf[strlen(buffer) - 1] != '\n') {
275                         log_message(LOG_WARNING,
276                                     "Config file line %d too long.\n", lineno);
277                         break;
278                 }
279
280                 while (isspace(*buf))
281                         buf++;
282
283                 if (*buf == '\0')
284                         /*
285                          * blank or all whitespace line
286                          */
287                         continue;
288
289                 if (*buf == '#')
290                         /*
291                          * comment line
292                          */
293                         continue;
294
295 #ifdef LOTS
296                 dprintf("lineno %d: '%s'\n", lineno, buf);
297 #endif
298                 str1 = strsep(&buf, "=");
299                 if (str1 && strcasecmp(str1, "VENDOR") == 0) {
300                         str1 = get_value(&buf);
301                         if (!str1) {
302                                 retval = -1;
303                                 break;
304                         }
305                         vendor_in = str1;
306
307                         str1 = strsep(&buf, "=");
308                         if (str1 && strcasecmp(str1, "MODEL") == 0) {
309                                 str1 = get_value(&buf);
310                                 if (!str1) {
311                                         retval = -1;
312                                         break;
313                                 }
314                                 model_in = str1;
315                                 str1 = strsep(&buf, "=");
316                         }
317                 }
318
319                 if (str1 && strcasecmp(str1, "OPTIONS") == 0) {
320                         str1 = get_value(&buf);
321                         if (!str1) {
322                                 retval = -1;
323                                 break;
324                         }
325                         options_in = str1;
326                 }
327                 dprintf("config file line %d:"
328                         " vendor '%s'; model '%s'; options '%s'\n",
329                         lineno, vendor_in, model_in, options_in);
330                 /*
331                  * Only allow: [vendor=foo[,model=bar]]options=stuff
332                  */
333                 if (!options_in || (!vendor_in && model_in)) {
334                         log_message(LOG_WARNING,
335                                     "Error parsing config file line %d '%s'\n",
336                                     lineno, buffer);
337                         retval = -1;
338                         break;
339                 }
340                 if (vendor == NULL) {
341                         if (vendor_in == NULL) {
342                                 dprintf("matched global option\n");
343                                 break;
344                         }
345                 } else if ((vendor_in && strncmp(vendor, vendor_in,
346                                                  strlen(vendor_in)) == 0) &&
347                            (!model_in || (strncmp(model, model_in,
348                                                   strlen(model_in)) == 0))) {
349                                 /*
350                                  * Matched vendor and optionally model.
351                                  *
352                                  * Note: a short vendor_in or model_in can
353                                  * give a partial match (that is FOO
354                                  * matches FOOBAR).
355                                  */
356                                 dprintf("matched vendor/model\n");
357                                 break;
358                 } else {
359                         dprintf("no match\n");
360                 }
361         }
362
363         if (retval == 0) {
364                 if (vendor_in != NULL || model_in != NULL ||
365                     options_in != NULL) {
366                         /*
367                          * Something matched. Allocate newargv, and store
368                          * values found in options_in.
369                          */
370                         strcpy(buffer, options_in);
371                         c = argc_count(buffer) + 2;
372                         *newargv = calloc(c, sizeof(**newargv));
373                         if (!*newargv) {
374                                 log_message(LOG_WARNING,
375                                             "Can't allocate memory.\n");
376                                 retval = -1;
377                         } else {
378                                 *argc = c;
379                                 c = 0;
380                                 /*
381                                  * argv[0] at 0 is skipped by getopt, but
382                                  * store the buffer address there for
383                                  * alter freeing.
384                                  */
385                                 (*newargv)[c] = buffer;
386                                 for (c = 1; c < *argc; c++)
387                                         (*newargv)[c] = strsep(&buffer, " ");
388                         }
389                 } else {
390                         /*
391                          * No matches.
392                          */
393                         retval = 1;
394                 }
395         }
396         if (retval != 0)
397                 free(buffer);
398         fclose(fd);
399         return retval;
400 }
401
402 static int set_options(int argc, char **argv, const char *short_opts,
403                        char *target, char *maj_min_dev)
404 {
405         int option;
406
407         /*
408          * optind is a global extern used by getopt. Since we can call
409          * set_options twice (once for command line, and once for config
410          * file) we have to reset this back to 1. [Note glibc handles
411          * setting this to 0, but klibc does not.]
412          */
413         optind = 1;
414         while (1) {
415                 option = getopt(argc, argv, short_options);
416                 if (option == -1)
417                         break;
418
419                 if (optarg)
420                         dprintf("option '%c' arg '%s'\n", option, optarg);
421                 else
422                         dprintf("option '%c'\n", option);
423
424                 switch (option) {
425                 case 'b':
426                         all_good = 0;
427                         break;
428
429                 case 'c':
430                         default_callout = optarg;
431                         break;
432
433                 case 'd':
434                         dev_specified = 1;
435                         strncpy(maj_min_dev, optarg, MAX_NAME_LEN);
436                         break;
437
438                 case 'e':
439                         use_stderr = 1;
440                         break;
441
442                 case 'f':
443                         strncpy(config_file, optarg, MAX_NAME_LEN);
444                         break;
445
446                 case 'g':
447                         all_good = 1;
448                         break;
449
450                 case 'i':
451                         display_bus_id = 1;
452                         break;
453
454                 case 'p':
455                         if (strcmp(optarg, "0x80") == 0) {
456                                 default_page_code = 0x80;
457                         } else if (strcmp(optarg, "0x83") == 0) {
458                                 default_page_code = 0x83;
459                         } else {
460                                 log_message(LOG_WARNING,
461                                             "Unknown page code '%s'\n", optarg);
462                                 return -1;
463                         }
464                         break;
465
466                 case 's':
467                         sys_specified = 1;
468                         strncpy(target, sysfs_mnt_path, MAX_NAME_LEN);
469                         strncat(target, optarg, MAX_NAME_LEN);
470                         break;
471
472                 case 'v':
473                         debug++;
474                         break;
475
476                 case 'V':
477                         log_message(LOG_WARNING, "scsi_id version: %s\n",
478                                     SCSI_ID_VERSION);
479                         exit(0);
480                         break;
481
482                 default:
483                         log_message(LOG_WARNING,
484                                     "Unknown or bad option '%c' (0x%x)\n",
485                                     option, option);
486                         return -1;
487                 }
488         }
489         return 0;
490 }
491
492 static int per_dev_options(struct sysfs_device *scsi_dev, int *good_bad,
493                            int *page_code, char *callout)
494 {
495         int retval;
496         int newargc;
497         char **newargv = NULL;
498         char vendor[MAX_ATTR_LEN];
499         char model[MAX_ATTR_LEN];
500         int option;
501
502         *good_bad = all_good;
503         *page_code = default_page_code;
504         if (default_callout && (callout != default_callout))
505                 strncpy(callout, default_callout, MAX_NAME_LEN);
506         else
507                 callout[0] = '\0';
508
509         if (sysfs_get_attr(scsi_dev->path, "vendor", vendor, MAX_ATTR_LEN)) {
510                 log_message(LOG_WARNING, "%s: cannot get vendor attribute\n",
511                             scsi_dev->name);
512                 return -1;
513         }
514
515         if (sysfs_get_attr(scsi_dev->path, "model", model, MAX_ATTR_LEN)) {
516                 log_message(LOG_WARNING, "%s: cannot get model attribute\n",
517                             scsi_dev->name);
518                 return -1;
519         }
520
521         retval = get_file_options(vendor, model, &newargc, &newargv);
522
523         optind = 1; /* reset this global extern */
524         while (retval == 0) {
525                 option = getopt(newargc, newargv, dev_short_options);
526                 if (option == -1)
527                         break;
528
529                 if (optarg)
530                         dprintf("option '%c' arg '%s'\n", option, optarg);
531                 else
532                         dprintf("option '%c'\n", option);
533
534                 switch (option) {
535                 case 'b':
536                         *good_bad = 0;
537                         break;
538
539                 case 'c':
540                         strncpy(callout, default_callout, MAX_NAME_LEN);
541                         break;
542
543                 case 'g':
544                         *good_bad = 1;
545                         break;
546
547                 case 'p':
548                         if (strcmp(optarg, "0x80") == 0) {
549                                 *page_code = 0x80;
550                         } else if (strcmp(optarg, "0x83") == 0) {
551                                 *page_code = 0x83;
552                         } else {
553                                 log_message(LOG_WARNING,
554                                             "Unknown page code '%s'\n", optarg);
555                                 retval = -1;
556                         }
557                         break;
558
559                 default:
560                         log_message(LOG_WARNING,
561                                     "Unknown or bad option '%c' (0x%x)\n",
562                                     option, option);
563                         retval = -1;
564                         break;
565                 }
566         }
567
568         if (newargv) {
569                 free(newargv[0]);
570                 free(newargv);
571         }
572         return retval;
573 }
574
575 /*
576  * scsi_id: try to get an id, if one is found, printf it to stdout.
577  * returns a value passed to exit() - 0 if printed an id, else 1. This
578  * could be expanded, for example, if we want to report a failure like no
579  * memory etc. return 2, and return 1 for expected cases (like broken
580  * device found) that do not print an id.
581  */
582 static int scsi_id(const char *target_path, char *maj_min_dev)
583 {
584         int retval;
585         int dev_type = 0;
586         char serial[MAX_SERIAL_LEN];
587         struct sysfs_class_device *class_dev; /* of target_path */
588         struct sysfs_class_device *class_dev_parent; /* for partitions */
589         struct sysfs_device *scsi_dev; /* the scsi_device */
590         int good_dev;
591         int page_code;
592         char callout[MAX_NAME_LEN];
593
594         dprintf("target_path %s\n", target_path);
595
596         /*
597          * Ugly: depend on the sysfs path to tell us whether this is a
598          * block or char device. This should probably be encoded in the
599          * "dev" along with the major/minor.
600          */
601         if (has_sysfs_prefix(target_path, "/block")) {
602                 dev_type = S_IFBLK;
603         } else if (has_sysfs_prefix(target_path, "/class")) {
604                 dev_type = S_IFCHR;
605         } else {
606                 if (!hotplug_mode) {
607                         log_message(LOG_WARNING,
608                                     "Non block or class device '%s'\n",
609                                     target_path);
610                         return 1;
611                 } else {
612                         /*
613                          * Expected in some cases.
614                          */
615                         dprintf("Non block or class device\n");
616                         return 0;
617                 }
618         }
619
620         class_dev = sysfs_open_class_device_path(target_path);
621         if (!class_dev) {
622                 log_message(LOG_WARNING, "open class %s failed: %s\n",
623                             target_path, strerror(errno));
624                 return 1;
625         }
626         class_dev_parent = sysfs_get_classdev_parent(class_dev);
627         dprintf("class_dev 0x%p; class_dev_parent 0x%p\n", class_dev,
628                 class_dev_parent);
629         if (class_dev_parent) {
630                 scsi_dev = sysfs_get_classdev_device(class_dev_parent);
631         } else {
632                 scsi_dev = sysfs_get_classdev_device(class_dev);
633         }
634
635         /*
636          * The close of scsi_dev will close class_dev or class_dev_parent.
637          */
638
639         /*
640          * We assume we are called after the device is completely ready,
641          * so we don't have to loop here like udev. (And we are usually
642          * called via udev.)
643          */
644         if (!scsi_dev) {
645                 /*
646                  * errno is not set if we can't find the device link, so
647                  * don't print it out here.
648                  */
649                 log_message(LOG_WARNING, "Cannot find sysfs device associated with %s\n",
650                             target_path);
651                 return 1;
652         }
653
654
655         /*
656          * Allow only scsi devices.
657          *
658          * Other block devices can support SG IO, but only ide-cd does, so
659          * for now, don't bother with anything else.
660          */
661         if (strcmp(scsi_dev->bus, "scsi") != 0) {
662                 if (hotplug_mode)
663                         /*
664                          * Expected in some cases.
665                          */
666                         dprintf("%s is not a scsi device\n", target_path);
667                 else
668                         log_message(LOG_WARNING, "%s is not a scsi device\n",
669                                     target_path);
670                 return 1;
671         }
672
673         /*
674          * mknod a temp dev to communicate with the device.
675          *
676          * XXX pass down class_dev or class_dev_parent.
677          */
678         if (!dev_specified && create_tmp_dev(target_path, maj_min_dev,
679                                              dev_type)) {
680                 dprintf("create_tmp_dev failed\n");
681                 return 1;
682         }
683
684         /*
685          * Get any per device (vendor + model) options from the config
686          * file.
687          */
688         retval = per_dev_options(scsi_dev, &good_dev, &page_code, callout);
689         dprintf("per dev options: good %d; page code 0x%x; callout '%s'\n",
690                 good_dev, page_code, callout);
691
692         if (!good_dev) {
693                 retval = 1;
694         } else if (callout[0] != '\0') {
695                 /*
696                  * XXX Disabled for now ('c' is not in any options[]).
697                  */
698                 retval = 1;
699         } else if (scsi_get_serial(scsi_dev, maj_min_dev, page_code,
700                                    serial, MAX_SERIAL_LEN)) {
701                 retval = 1;
702         } else {
703                 retval = 0;
704         }
705         if (!retval) {
706                 if (display_bus_id)
707                         printf("%s: ", scsi_dev->name);
708                 printf("%s", serial);
709                 if (!hotplug_mode)
710                         printf("\n");
711                 dprintf("%s\n", serial);
712                 retval = 0;
713         }
714         sysfs_close_device(scsi_dev);
715
716         if (!dev_specified)
717                 unlink(maj_min_dev);
718
719         return retval;
720 }
721
722 int main(int argc, char **argv)
723 {
724         int retval;
725         char *devpath;
726         char target_path[MAX_NAME_LEN];
727         char maj_min_dev[MAX_NAME_LEN];
728         int newargc;
729         char **newargv;
730
731         if (getenv("DEBUG"))
732                 debug++;
733
734         if ((argc == 2) && (argv[1][0] != '-')) {
735                 hotplug_mode = 1;
736                 dprintf("hotplug assumed\n");
737         }
738
739         dprintf("argc is %d\n", argc);
740         if (sysfs_get_mnt_path(sysfs_mnt_path, MAX_NAME_LEN)) {
741                 log_message(LOG_WARNING, "sysfs_get_mnt_path failed: %s\n",
742                         strerror(errno));
743                 exit(1);
744         }
745
746         if (hotplug_mode) {
747                 /*
748                  * There is a kernel race creating attributes, if called
749                  * directly, uncomment the sleep.
750                  */
751                 /* sleep(1); */
752
753                 devpath = getenv("DEVPATH");
754                 if (!devpath) {
755                         log_message(LOG_WARNING, "DEVPATH is not set\n");
756                         exit(1);
757                 }
758                 sys_specified = 1;
759
760                 strncpy(target_path, sysfs_mnt_path, MAX_NAME_LEN);
761                 strncat(target_path, devpath, MAX_NAME_LEN);
762         } else {
763                 if (set_options(argc, argv, short_options, target_path,
764                                 maj_min_dev) < 0)
765                         exit(1);
766         }
767
768         /*
769          * Override any command line options set via the config file. This
770          * is the only way to set options when in hotplug mode.
771          */
772         newargv = NULL;
773         retval = get_file_options(NULL, NULL, &newargc, &newargv);
774         if (retval < 0) {
775                 exit(1);
776         } else if (newargv && (retval == 0)) {
777                 if (set_options(newargc, newargv, short_options, target_path,
778                                 maj_min_dev) < 0)
779                         exit(1);
780                 free(newargv);
781         }
782
783         if (!sys_specified) {
784                 log_message(LOG_WARNING, "-s must be specified\n");
785                 exit(1);
786         }
787
788         retval = scsi_id(target_path, maj_min_dev);
789         exit(retval);
790 }