]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/eject.c
eject: Check host_status and driver_status when using SG_IO.
[thirdparty/util-linux.git] / sys-utils / eject.c
1 /*
2 * Copyright (C) 1994-2005 Jeff Tranter (tranter@pobox.com)
3 * Copyright (C) 2012 Karel Zak <kzak@redhat.com>
4 * Copyright (C) Michal Luscon <mluscon@redhat.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <err.h>
28 #include <stdarg.h>
29
30 #include <getopt.h>
31 #include <errno.h>
32 #include <regex.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/ioctl.h>
36 #include <sys/wait.h>
37 #include <sys/mtio.h>
38 #include <linux/cdrom.h>
39 #include <linux/fd.h>
40 #include <sys/mount.h>
41 #include <scsi/scsi.h>
42 #include <scsi/sg.h>
43 #include <scsi/scsi_ioctl.h>
44 #include <sys/time.h>
45
46 #include <libmount.h>
47
48 #include "c.h"
49 #include "closestream.h"
50 #include "nls.h"
51 #include "strutils.h"
52 #include "xalloc.h"
53 #include "pathnames.h"
54 #include "sysfs.h"
55
56 /*
57 * sg_io_hdr_t driver_status -- see kernel include/scsi/scsi.h
58 */
59 #ifndef DRIVER_SENSE
60 # define DRIVER_SENSE 0x08
61 #endif
62
63
64 #define EJECT_DEFAULT_DEVICE "/dev/cdrom"
65
66
67 /* Used by the toggle_tray() function. If ejecting the tray takes this
68 * time or less, the tray was probably already ejected, so we close it
69 * again.
70 */
71 #define TRAY_WAS_ALREADY_OPEN_USECS 200000 /* about 0.2 seconds */
72
73 /* eject(1) is able to eject only 'removable' devices (attribute in /sys)
74 * _or_ devices connected by hotplug subsystem.
75 */
76 static const char * const hotplug_subsystems[] = {
77 "usb",
78 "ieee1394",
79 "pcmcia",
80 "mmc",
81 "ccw"
82 };
83
84 /* Global Variables */
85 static int a_option; /* command flags and arguments */
86 static int c_option;
87 static int d_option;
88 static int f_option;
89 static int F_option;
90 static int n_option;
91 static int q_option;
92 static int r_option;
93 static int s_option;
94 static int t_option;
95 static int T_option;
96 static int X_option;
97 static int v_option;
98 static int x_option;
99 static int p_option;
100 static int m_option;
101 static int M_option;
102 static int i_option;
103 static int a_arg;
104 static int i_arg;
105 static long int c_arg;
106 static long int x_arg;
107
108 struct libmnt_table *mtab;
109 struct libmnt_cache *cache;
110
111 static void vinfo(const char *fmt, va_list va)
112 {
113 fprintf(stdout, "%s: ", program_invocation_short_name);
114 vprintf(fmt, va);
115 fputc('\n', stdout);
116 }
117
118 static inline void verbose(const char *fmt, ...)
119 {
120 va_list va;
121
122 if (!v_option)
123 return;
124
125 va_start(va, fmt);
126 vinfo(fmt, va);
127 va_end(va);
128 }
129
130 static inline void info(const char *fmt, ...)
131 {
132 va_list va;
133 va_start(va, fmt);
134 vinfo(fmt, va);
135 va_end(va);
136 }
137
138 static void __attribute__ ((__noreturn__)) usage(FILE * out)
139 {
140 fputs(USAGE_HEADER, out);
141
142 fprintf(out,
143 _(" %s [options] [<device>|<mountpoint>]\n"), program_invocation_short_name);
144
145 fputs(USAGE_OPTIONS, out);
146 fputs(_(" -a, --auto <on|off> turn auto-eject feature on or off\n"
147 " -c, --changerslot <slot> switch discs on a CD-ROM changer\n"
148 " -d, --default display default device\n"
149 " -f, --floppy eject floppy\n"
150 " -F, --force don't care about device type\n"
151 " -i, --manualeject <on|off> toggle manual eject protection on/off\n"
152 " -m, --no-unmount do not unmount device even if it is mounted\n"
153 " -M, --no-partitions-unmount do not unmount another partitions\n"
154 " -n, --noop don't eject, just show device found\n"
155 " -p, --proc use /proc/mounts instead of /etc/mtab\n"
156 " -q, --tape eject tape\n"
157 " -r, --cdrom eject CD-ROM\n"
158 " -s, --scsi eject SCSI device\n"
159 " -t, --trayclose close tray\n"
160 " -T, --traytoggle toggle tray\n"
161 " -v, --verbose enable verbose output\n"
162 " -x, --cdspeed <speed> set CD-ROM max speed\n"
163 " -X, --listspeed list CD-ROM available speeds\n"),
164 out);
165
166 fputs(USAGE_SEPARATOR, out);
167 fputs(USAGE_HELP, out);
168 fputs(USAGE_VERSION, out);
169
170 fputs(_("\nBy default tries -r, -s, -f, and -q in order until success.\n"), out);
171 fprintf(out, USAGE_MAN_TAIL("eject(1)"));
172
173 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
174 }
175
176
177 /* Handle command line options. */
178 static void parse_args(int argc, char **argv, char **device)
179 {
180 static const struct option long_opts[] =
181 {
182 {"auto", required_argument, NULL, 'a'},
183 {"cdrom", no_argument, NULL, 'r'},
184 {"cdspeed", required_argument, NULL, 'x'},
185 {"changerslot", required_argument, NULL, 'c'},
186 {"default", no_argument, NULL, 'd'},
187 {"floppy", no_argument, NULL, 'f'},
188 {"force", no_argument, NULL, 'F'},
189 {"help", no_argument, NULL, 'h'},
190 {"listspeed", no_argument, NULL, 'X'},
191 {"manualeject", required_argument, NULL, 'i'},
192 {"noop", no_argument, NULL, 'n'},
193 {"no-unmount", no_argument, NULL, 'm'},
194 {"no-partitions-unmount", no_argument, NULL, 'M' },
195 {"proc", no_argument, NULL, 'p'},
196 {"scsi", no_argument, NULL, 's'},
197 {"tape", no_argument, NULL, 'q'},
198 {"trayclose", no_argument, NULL, 't'},
199 {"traytoggle", no_argument, NULL, 'T'},
200 {"verbose", no_argument, NULL, 'v'},
201 {"version", no_argument, NULL, 'V'},
202 {0, 0, 0, 0}
203 };
204 int c;
205
206 while ((c = getopt_long(argc, argv,
207 "a:c:i:x:dfFhnqrstTXvVpmM", long_opts, NULL)) != -1) {
208 switch (c) {
209 case 'a':
210 a_option = 1;
211 if (!strcmp(optarg, "0") || !strcmp(optarg, "off"))
212 a_arg = 0;
213 else if (!strcmp(optarg, "1") || !strcmp(optarg, "on"))
214 a_arg = 1;
215 else
216 errx(EXIT_FAILURE, _("invalid argument to --auto/-a option"));
217 break;
218 case 'c':
219 c_option = 1;
220 c_arg = strtoul_or_err(optarg, _("invalid argument to --changerslot/-c option"));
221 break;
222 case 'x':
223 x_option = 1;
224 x_arg = strtoul_or_err(optarg, _("invalid argument to --cdspeed/-x option"));
225 break;
226 case 'd':
227 d_option = 1;
228 break;
229 case 'f':
230 f_option = 1;
231 break;
232 case 'F':
233 F_option = 1;
234 break;
235 case 'h':
236 usage(stdout);
237 break;
238 case 'i':
239 i_option = 1;
240 if (!strcmp(optarg, "0") || !strcmp(optarg, "off"))
241 i_arg = 0;
242 else if (!strcmp(optarg, "1") || !strcmp(optarg, "on"))
243 i_arg = 1;
244 else
245 errx(EXIT_FAILURE, _("invalid argument to --manualeject/-i option"));
246 break;
247 case 'm':
248 m_option = 1;
249 break;
250 case 'M':
251 M_option = 1;
252 break;
253 case 'n':
254 n_option = 1;
255 break;
256 case 'p':
257 p_option = 1;
258 break;
259 case 'q':
260 q_option = 1;
261 break;
262 case 'r':
263 r_option = 1;
264 break;
265 case 's':
266 s_option = 1;
267 break;
268 case 't':
269 t_option = 1;
270 break;
271 case 'T':
272 T_option = 1;
273 break;
274 case 'X':
275 X_option = 1;
276 break;
277 case 'v':
278 v_option = 1;
279 break;
280 case 'V':
281 printf(UTIL_LINUX_VERSION);
282 exit(EXIT_SUCCESS);
283 break;
284 default:
285 case '?':
286 usage(stderr);
287 break;
288 }
289 }
290
291 /* check for a single additional argument */
292 if ((argc - optind) > 1)
293 errx(EXIT_FAILURE, _("too many arguments"));
294
295 if ((argc - optind) == 1)
296 *device = xstrdup(argv[optind]);
297 }
298
299 /*
300 * Given name, such as foo, see if any of the following exist:
301 *
302 * foo (if foo starts with '.' or '/')
303 * /dev/foo
304 *
305 * If found, return the full path. If not found, return 0.
306 * Returns pointer to dynamically allocated string.
307 */
308 static char *find_device(const char *name)
309 {
310 if (!name)
311 return NULL;
312
313 if ((*name == '.' || *name == '/') && access(name, F_OK) == 0)
314 return xstrdup(name);
315 else {
316 char buf[PATH_MAX];
317
318 snprintf(buf, sizeof(buf), "/dev/%s", name);
319 if (access(buf, F_OK) == 0)
320 return xstrdup(buf);
321 }
322
323 return NULL;
324 }
325
326 /* Set or clear auto-eject mode. */
327 static void auto_eject(int fd, int on)
328 {
329 int status = -1;
330
331 #if defined(CDROM_SET_OPTIONS) && defined(CDROM_CLEAR_OPTIONS)
332 if (on)
333 status = ioctl(fd, CDROM_SET_OPTIONS, CDO_AUTO_EJECT);
334 else
335 status = ioctl(fd, CDROM_CLEAR_OPTIONS, CDO_AUTO_EJECT);
336 #else
337 errno = ENOSYS;
338 #endif
339 if (status < 0)
340 err(EXIT_FAILURE,_("CD-ROM auto-eject command failed"));
341 }
342
343 /*
344 * Stops CDROM from opening on manual eject pressing the button.
345 * This can be useful when you carry your laptop
346 * in your bag while it's on and no CD inserted in it's drive.
347 * Implemented as found in Documentation/ioctl/cdrom.txt
348 *
349 * TODO: Maybe we should check this also:
350 * EDRIVE_CANT_DO_THIS Door lock function not supported.
351 * EBUSY Attempt to unlock when multiple users
352 * have the drive open and not CAP_SYS_ADMIN
353 */
354 static void manual_eject(int fd, int on)
355 {
356 if (ioctl(fd, CDROM_LOCKDOOR, on) < 0)
357 err(EXIT_FAILURE, _("CD-ROM lock door command failed"));
358
359 if (on)
360 info(_("CD-Drive may NOT be ejected with device button"));
361 else
362 info(_("CD-Drive may be ejected with device button"));
363 }
364
365 /*
366 * Changer select. CDROM_SELECT_DISC is preferred, older kernels used
367 * CDROMLOADFROMSLOT.
368 */
369 static void changer_select(int fd, int slot)
370 {
371 #ifdef CDROM_SELECT_DISC
372 if (ioctl(fd, CDROM_SELECT_DISC, slot) < 0)
373 err(EXIT_FAILURE, _("CD-ROM select disc command failed"));
374
375 #elif defined CDROMLOADFROMSLOT
376 if (ioctl(fd, CDROMLOADFROMSLOT, slot) != 0)
377 err(EXIT_FAILURE, _("CD-ROM load from slot command failed"));
378 #else
379 warnx(_("IDE/ATAPI CD-ROM changer not supported by this kernel\n") );
380 #endif
381 }
382
383 /*
384 * Close tray. Not supported by older kernels.
385 */
386 static void close_tray(int fd)
387 {
388 int status;
389
390 #if defined(CDROMCLOSETRAY) || defined(CDIOCCLOSE)
391 #if defined(CDROMCLOSETRAY)
392 status = ioctl(fd, CDROMCLOSETRAY);
393 #elif defined(CDIOCCLOSE)
394 status = ioctl(fd, CDIOCCLOSE);
395 #endif
396 if (status != 0)
397 err(EXIT_FAILURE, _("CD-ROM tray close command failed"));
398 #else
399 warnx(_("CD-ROM tray close command not supported by this kernel\n"));
400 #endif
401 }
402
403 /*
404 * Eject using CDROMEJECT ioctl.
405 */
406 static int eject_cdrom(int fd)
407 {
408 #if defined(CDROMEJECT)
409 int ret = ioctl(fd, CDROM_LOCKDOOR, 0);
410 if (ret < 0)
411 return 0;
412 return ioctl(fd, CDROMEJECT) >= 0;
413 #elif defined(CDIOCEJECT)
414 return ioctl(fd, CDIOCEJECT) >= 0;
415 #else
416 warnx(_("CD-ROM eject unsupported"));
417 errno = ENOSYS;
418 return 0;
419 #endif
420 }
421
422 /*
423 * Toggle tray.
424 *
425 * Written by Benjamin Schwenk <benjaminschwenk@yahoo.de> and
426 * Sybren Stuvel <sybren@thirdtower.com>
427 *
428 * Not supported by older kernels because it might use
429 * CloseTray().
430 *
431 */
432 static void toggle_tray(int fd)
433 {
434 struct timeval time_start, time_stop;
435 int time_elapsed;
436
437 #ifdef CDROM_DRIVE_STATUS
438 /* First ask the CDROM for info, otherwise fall back to manual. */
439 switch (ioctl(fd, CDROM_DRIVE_STATUS)) {
440 case CDS_TRAY_OPEN:
441 close_tray(fd);
442 return;
443
444 case CDS_NO_DISC:
445 case CDS_DISC_OK:
446 if (!eject_cdrom(fd))
447 err(EXIT_FAILURE, _("CD-ROM eject command failed"));
448 return;
449 case CDS_NO_INFO:
450 warnx(_("no CD-ROM information available"));
451 return;
452 case CDS_DRIVE_NOT_READY:
453 warnx(_("CD-ROM drive is not ready"));
454 return;
455 default:
456 abort();
457 }
458 #endif
459
460 /* Try to open the CDROM tray and measure the time therefor
461 * needed. In my experience the function needs less than 0.05
462 * seconds if the tray was already open, and at least 1.5 seconds
463 * if it was closed. */
464 gettimeofday(&time_start, NULL);
465
466 /* Send the CDROMEJECT command to the device. */
467 if (!eject_cdrom(fd))
468 err(EXIT_FAILURE, _("CD-ROM eject command failed"));
469
470 /* Get the second timestamp, to measure the time needed to open
471 * the tray. */
472 gettimeofday(&time_stop, NULL);
473
474 time_elapsed = (time_stop.tv_sec * 1000000 + time_stop.tv_usec) -
475 (time_start.tv_sec * 1000000 + time_start.tv_usec);
476
477 /* If the tray "opened" too fast, we can be nearly sure, that it
478 * was already open. In this case, close it now. Else the tray was
479 * closed before. This would mean that we are done. */
480 if (time_elapsed < TRAY_WAS_ALREADY_OPEN_USECS)
481 close_tray(fd);
482 }
483
484 /*
485 * Select Speed of CD-ROM drive.
486 * Thanks to Roland Krivanek (krivanek@fmph.uniba.sk)
487 * http://dmpc.dbp.fmph.uniba.sk/~krivanek/cdrom_speed/
488 */
489 static void select_speed(int fd, int speed)
490 {
491 #ifdef CDROM_SELECT_SPEED
492 if (ioctl(fd, CDROM_SELECT_SPEED, speed) != 0)
493 err(EXIT_FAILURE, _("CD-ROM select speed command failed"));
494 #else
495 warnx(_("CD-ROM select speed command not supported by this kernel"));
496 #endif
497 }
498
499 /*
500 * Read Speed of CD-ROM drive. From Linux 2.6.13, the current speed
501 * is correctly reported
502 */
503 static int read_speed(const char *devname)
504 {
505 int drive_number = -1;
506 char *name;
507 FILE *f;
508
509 f = fopen(_PATH_PROC_CDROMINFO, "r");
510 if (!f)
511 err(EXIT_FAILURE, _("cannot open %s"), _PATH_PROC_CDROMINFO);
512
513 name = strrchr(devname, '/') + 1;
514
515 while (name && !feof(f)) {
516 char line[512];
517 char *str;
518
519 if (!fgets(line, sizeof(line), f))
520 break;
521
522 /* find drive number in line "drive name" */
523 if (drive_number == -1) {
524 if (strncmp(line, "drive name:", 11) == 0) {
525 str = strtok(&line[11], "\t ");
526 drive_number = 0;
527 while (str && strncmp(name, str, strlen(name)) != 0) {
528 drive_number++;
529 str = strtok(NULL, "\t ");
530 if (!str)
531 errx(EXIT_FAILURE,
532 _("%s: failed to finding CD-ROM name"),
533 _PATH_PROC_CDROMINFO);
534 }
535 }
536 /* find line "drive speed" and read the correct speed */
537 } else {
538 if (strncmp(line, "drive speed:", 12) == 0) {
539 int i;
540
541 str = strtok(&line[12], "\t ");
542 for (i = 1; i < drive_number; i++)
543 str = strtok(NULL, "\t ");
544
545 if (!str)
546 errx(EXIT_FAILURE,
547 _("%s: failed to read speed"),
548 _PATH_PROC_CDROMINFO);
549 fclose(f);
550 return atoi(str);
551 }
552 }
553 }
554
555 errx(EXIT_FAILURE, _("failed to read speed"));
556 }
557
558 /*
559 * List Speed of CD-ROM drive.
560 */
561 static void list_speeds(const char *name, int fd)
562 {
563 #ifdef CDROM_SELECT_SPEED
564 int max_speed, curr_speed = 0, prev_speed;
565
566 select_speed(fd, 0);
567 max_speed = read_speed(name);
568
569 while (curr_speed < max_speed) {
570 prev_speed = curr_speed;
571 select_speed(fd, prev_speed + 1);
572 curr_speed = read_speed(name);
573 if (curr_speed > prev_speed)
574 printf("%d ", curr_speed);
575 else
576 curr_speed = prev_speed + 1;
577 }
578
579 printf("\n");
580 #else
581 warnx(_("CD-ROM select speed command not supported by this kernel"));
582 #endif
583 }
584
585 /*
586 * Eject using SCSI SG_IO commands. Return 1 if successful, 0 otherwise.
587 */
588 static int eject_scsi(int fd)
589 {
590 int status, k;
591 sg_io_hdr_t io_hdr;
592 unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0};
593 unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0};
594 unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 2, 0};
595 unsigned char inqBuff[2];
596 unsigned char sense_buffer[32];
597
598 if ((ioctl(fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
599 verbose(_("not an sg device, or old sg driver"));
600 return 0;
601 }
602
603 memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
604 io_hdr.interface_id = 'S';
605 io_hdr.cmd_len = 6;
606 io_hdr.mx_sb_len = sizeof(sense_buffer);
607 io_hdr.dxfer_direction = SG_DXFER_NONE;
608 io_hdr.dxfer_len = 0;
609 io_hdr.dxferp = inqBuff;
610 io_hdr.sbp = sense_buffer;
611 io_hdr.timeout = 10000;
612
613 io_hdr.cmdp = allowRmBlk;
614 status = ioctl(fd, SG_IO, (void *)&io_hdr);
615 if (status < 0 || io_hdr.host_status || io_hdr.driver_status)
616 return 0;
617
618 io_hdr.cmdp = startStop1Blk;
619 status = ioctl(fd, SG_IO, (void *)&io_hdr);
620 if (status < 0 || io_hdr.host_status)
621 return 0;
622
623 /* Ignore errors when there is not medium -- in this case driver sense
624 * buffer sets MEDIUM NOT PRESENT (3a) bit. For more details see:
625 * http://www.tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/SCSI-Programming-HOWTO-22.html#sec-sensecodes
626 * -- kzak Jun 2013
627 */
628 if (io_hdr.driver_status != 0 &&
629 !(io_hdr.driver_status == DRIVER_SENSE && io_hdr.sbp &&
630 io_hdr.sbp[12] == 0x3a))
631 return 0;
632
633 io_hdr.cmdp = startStop2Blk;
634 status = ioctl(fd, SG_IO, (void *)&io_hdr);
635 if (status < 0 || io_hdr.host_status || io_hdr.driver_status)
636 return 0;
637
638 /* force kernel to reread partition table when new disc inserted */
639 status = ioctl(fd, BLKRRPART);
640 return 1;
641 }
642
643 /*
644 * Eject using FDEJECT ioctl. Return 1 if successful, 0 otherwise.
645 */
646 static int eject_floppy(int fd)
647 {
648 return ioctl(fd, FDEJECT) >= 0;
649 }
650
651
652 /*
653 * Rewind and eject using tape ioctl. Return 1 if successful, 0 otherwise.
654 */
655 static int eject_tape(int fd)
656 {
657 struct mtop op = { .mt_op = MTOFFL, .mt_count = 0 };
658
659 return ioctl(fd, MTIOCTOP, &op) >= 0;
660 }
661
662
663 /* umount a device. */
664 static void umount_one(const char *name)
665 {
666 int status;
667
668 if (!name)
669 return;
670
671 verbose(_("%s: unmounting"), name);
672
673 switch (fork()) {
674 case 0: /* child */
675 if (setgid(getgid()) < 0)
676 err(EXIT_FAILURE, _("cannot set group id"));
677
678 if (setuid(getuid()) < 0)
679 err(EXIT_FAILURE, _("cannot set user id"));
680
681 if (p_option)
682 execl("/bin/umount", "/bin/umount", name, "-n", NULL);
683 else
684 execl("/bin/umount", "/bin/umount", name, NULL);
685
686 errx(EXIT_FAILURE, _("unable to exec /bin/umount of `%s'"), name);
687
688 case -1:
689 warn( _("unable to fork"));
690 break;
691
692 default: /* parent */
693 wait(&status);
694 if (WIFEXITED(status) == 0)
695 errx(EXIT_FAILURE,
696 _("unmount of `%s' did not exit normally"), name);
697
698 if (WEXITSTATUS(status) != 0)
699 errx(EXIT_FAILURE, _("unmount of `%s' failed\n"), name);
700 break;
701 }
702 }
703
704 /* Open a device file. */
705 static int open_device(const char *name)
706 {
707 int fd = open(name, O_RDWR|O_NONBLOCK);
708
709 if (fd < 0)
710 fd = open(name, O_RDONLY|O_NONBLOCK);
711 if (fd == -1)
712 err(EXIT_FAILURE, _("cannot open %s"), name);
713 return fd;
714 }
715
716 /*
717 * See if device has been mounted by looking in mount table. If so, set
718 * device name and mount point name, and return 1, otherwise return 0.
719 */
720 static int device_get_mountpoint(char **devname, char **mnt)
721 {
722 struct libmnt_fs *fs;
723 int rc;
724
725 *mnt = NULL;
726
727 if (!mtab) {
728 mtab = mnt_new_table();
729 if (!mtab)
730 err(EXIT_FAILURE, _("failed to initialize libmount table"));
731
732 cache = mnt_new_cache();
733 mnt_table_set_cache(mtab, cache);
734
735 if (p_option)
736 rc = mnt_table_parse_file(mtab, _PATH_PROC_MOUNTINFO);
737 else
738 rc = mnt_table_parse_mtab(mtab, NULL);
739 if (rc)
740 err(EXIT_FAILURE, _("failed to parse mount table"));
741 }
742
743 fs = mnt_table_find_source(mtab, *devname, MNT_ITER_BACKWARD);
744 if (!fs) {
745 /* maybe 'devname' is mountpoint rather than a real device */
746 fs = mnt_table_find_target(mtab, *devname, MNT_ITER_BACKWARD);
747 if (fs) {
748 free(*devname);
749 *devname = xstrdup(mnt_fs_get_source(fs));
750 }
751 }
752
753 if (fs)
754 *mnt = xstrdup(mnt_fs_get_target(fs));
755 return *mnt ? 0 : -1;
756 }
757
758 static char *get_disk_devname(const char *device)
759 {
760 struct stat st;
761 dev_t diskno = 0;
762 char diskname[128];
763
764 if (stat(device, &st) != 0)
765 return NULL;
766
767 /* get whole-disk devno */
768 if (sysfs_devno_to_wholedisk(st.st_rdev, diskname,
769 sizeof(diskname), &diskno) != 0)
770 return NULL;
771
772 return st.st_rdev == diskno ? NULL : find_device(diskname);
773 }
774
775 static int umount_partitions(const char *disk, int checkonly)
776 {
777 struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY;
778 dev_t devno;
779 DIR *dir = NULL;
780 struct dirent *d;
781 int count = 0;
782
783 devno = sysfs_devname_to_devno(disk, NULL);
784 if (sysfs_init(&cxt, devno, NULL) != 0)
785 return 0;
786
787 /* open /sys/block/<wholedisk> */
788 if (!(dir = sysfs_opendir(&cxt, NULL)))
789 goto done;
790
791 /* scan for partition subdirs */
792 while ((d = readdir(dir))) {
793 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
794 continue;
795
796 if (sysfs_is_partition_dirent(dir, d, disk)) {
797 char *mnt = NULL;
798 char *dev = find_device(d->d_name);
799
800 if (dev && device_get_mountpoint(&dev, &mnt) == 0) {
801 verbose(_("%s: mounted on %s"), dev, mnt);
802 if (!checkonly)
803 umount_one(mnt);
804 count++;
805 }
806 free(dev);
807 free(mnt);
808 }
809 }
810
811 done:
812 if (dir)
813 closedir(dir);
814 sysfs_deinit(&cxt);
815
816 return count;
817 }
818
819 static int is_hotpluggable_subsystem(const char *name)
820 {
821 size_t i;
822
823 for (i = 0; i < ARRAY_SIZE(hotplug_subsystems); i++)
824 if (strcmp(name, hotplug_subsystems[i]) == 0)
825 return 1;
826
827 return 0;
828 }
829
830 #define SUBSYSTEM_LINKNAME "/subsystem"
831
832 /*
833 * For example:
834 *
835 * chain: /sys/dev/block/../../devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/ \
836 * 1-1.2:1.0/host65/target65:0:0/65:0:0:0/block/sdb
837 *
838 * The function check if <chain>/subsystem symlink exists, if yes then returns
839 * basename of the readlink result, and remove the last subdirectory from the
840 * <chain> path.
841 */
842 static char *get_subsystem(char *chain, char *buf, size_t bufsz)
843 {
844 size_t len;
845 char *p;
846
847 if (!chain || !*chain)
848 return NULL;
849
850 len = strlen(chain);
851 if (len + sizeof(SUBSYSTEM_LINKNAME) > PATH_MAX)
852 return NULL;
853
854 do {
855 ssize_t sz;
856
857 /* append "/subsystem" to the path */
858 memcpy(chain + len, SUBSYSTEM_LINKNAME, sizeof(SUBSYSTEM_LINKNAME));
859
860 /* try if subsystem symlink exists */
861 sz = readlink(chain, buf, bufsz - 1);
862
863 /* remove last subsystem from chain */
864 chain[len] = '\0';
865 p = strrchr(chain, '/');
866 if (p) {
867 *p = '\0';
868 len = p - chain;
869 }
870
871 if (sz > 0) {
872 /* we found symlink to subsystem, return basename */
873 buf[sz] = '\0';
874 return basename(buf);
875 }
876
877 } while (p);
878
879 return NULL;
880 }
881
882 static int is_hotpluggable(const char* device)
883 {
884 struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY;
885 char devchain[PATH_MAX];
886 char subbuf[PATH_MAX];
887 dev_t devno;
888 int rc = 0;
889 ssize_t sz;
890 char *sub;
891
892 devno = sysfs_devname_to_devno(device, NULL);
893 if (sysfs_init(&cxt, devno, NULL) != 0)
894 return 0;
895
896 /* check /sys/dev/block/<maj>:<min>/removable attribute */
897 if (sysfs_read_int(&cxt, "removable", &rc) == 0 && rc == 1) {
898 verbose(_("%s: is removable device"), device);
899 goto done;
900 }
901
902 /* read /sys/dev/block/<maj>:<min> symlink */
903 sz = sysfs_readlink(&cxt, NULL, devchain, sizeof(devchain));
904 if (sz <= 0 || sz + sizeof(_PATH_SYS_DEVBLOCK "/") > sizeof(devchain))
905 goto done;
906
907 devchain[sz++] = '\0';
908
909 /* create absolute patch from the link */
910 memmove(devchain + sizeof(_PATH_SYS_DEVBLOCK "/") - 1, devchain, sz);
911 memcpy(devchain, _PATH_SYS_DEVBLOCK "/",
912 sizeof(_PATH_SYS_DEVBLOCK "/") - 1);
913
914 while ((sub = get_subsystem(devchain, subbuf, sizeof(subbuf)))) {
915 rc = is_hotpluggable_subsystem(sub);
916 if (rc) {
917 verbose(_("%s: connected by hotplug subsystem: %s"),
918 device, sub);
919 break;
920 }
921 }
922
923 done:
924 sysfs_deinit(&cxt);
925 return rc;
926 }
927
928
929 /* handle -x option */
930 static void set_device_speed(char *name)
931 {
932 int fd;
933
934 if (!x_option)
935 return;
936
937 if (x_arg == 0)
938 verbose(_("setting CD-ROM speed to auto"));
939 else
940 verbose(_("setting CD-ROM speed to %ldX"), x_arg);
941
942 fd = open_device(name);
943 select_speed(fd, x_arg);
944 exit(EXIT_SUCCESS);
945 }
946
947
948 /* main program */
949 int main(int argc, char **argv)
950 {
951 char *device = NULL;
952 char *disk = NULL;
953 char *mountpoint = NULL;
954 int worked = 0; /* set to 1 when successfully ejected */
955 int fd; /* file descriptor for device */
956
957 setlocale(LC_ALL,"");
958 bindtextdomain(PACKAGE, LOCALEDIR);
959 textdomain(PACKAGE);
960 atexit(close_stdout);
961
962 /* parse the command line arguments */
963 parse_args(argc, argv, &device);
964
965 /* handle -d option */
966 if (d_option) {
967 info(_("default device: `%s'"), EJECT_DEFAULT_DEVICE);
968 return EXIT_SUCCESS;
969 }
970
971 if (!device) {
972 device = mnt_resolve_path(EJECT_DEFAULT_DEVICE, NULL);
973 verbose(_("using default device `%s'"), device);
974 } else {
975 char *p;
976
977 if (device[strlen(device)-1] == '/')
978 device[strlen(device)-1] = '\0';
979
980 /* figure out full device or mount point name */
981 p = find_device(device);
982 if (p)
983 free(device);
984 else
985 p = device;
986
987 device = mnt_resolve_spec(p, NULL);
988 free(p);
989 }
990
991 if (!device)
992 errx(EXIT_FAILURE, _("%s: unable to find device"), device);
993
994 verbose(_("device name is `%s'"), device);
995
996 device_get_mountpoint(&device, &mountpoint);
997 if (mountpoint)
998 verbose(_("%s: mounted on %s"), device, mountpoint);
999 else
1000 verbose(_("%s: not mounted"), device);
1001
1002 disk = get_disk_devname(device);
1003 if (disk) {
1004 verbose(_("%s: disc device: %s (disk device will be used for eject)"), device, disk);
1005 free(device);
1006 device = disk;
1007 disk = NULL;
1008 } else {
1009 struct stat st;
1010
1011 if (stat(device, &st) != 0 || !S_ISBLK(st.st_mode))
1012 errx(EXIT_FAILURE, _("%s: not found mountpoint or device "
1013 "with the given name"), device);
1014
1015 verbose(_("%s: is whole-disk device"), device);
1016 }
1017
1018 if (F_option == 0 && is_hotpluggable(device) == 0)
1019 errx(EXIT_FAILURE, _("%s: is not hot-pluggable device"), device);
1020
1021 /* handle -n option */
1022 if (n_option) {
1023 info(_("device is `%s'"), device);
1024 verbose(_("exiting due to -n/--noop option"));
1025 return EXIT_SUCCESS;
1026 }
1027
1028 /* handle -i option */
1029 if (i_option) {
1030 fd = open_device(device);
1031 manual_eject(fd, i_arg);
1032 return EXIT_SUCCESS;
1033 }
1034
1035 /* handle -a option */
1036 if (a_option) {
1037 if (a_arg)
1038 verbose(_("%s: enabling auto-eject mode"), device);
1039 else
1040 verbose(_("%s: disabling auto-eject mode"), device);
1041 fd = open_device(device);
1042 auto_eject(fd, a_arg);
1043 return EXIT_SUCCESS;
1044 }
1045
1046 /* handle -t option */
1047 if (t_option) {
1048 verbose(_("%s: closing tray"), device);
1049 fd = open_device(device);
1050 close_tray(fd);
1051 set_device_speed(device);
1052 return EXIT_SUCCESS;
1053 }
1054
1055 /* handle -T option */
1056 if (T_option) {
1057 verbose(_("%s: toggling tray"), device);
1058 fd = open_device(device);
1059 toggle_tray(fd);
1060 set_device_speed(device);
1061 return EXIT_SUCCESS;
1062 }
1063
1064 /* handle -X option */
1065 if (X_option) {
1066 verbose(_("%s: listing CD-ROM speed"), device);
1067 fd = open_device(device);
1068 list_speeds(device, fd);
1069 return EXIT_SUCCESS;
1070 }
1071
1072 /* handle -x option only */
1073 if (!c_option)
1074 set_device_speed(device);
1075
1076
1077 /*
1078 * Unmount all partitions if -m is not specified; or umount given
1079 * mountpoint if -M is specified, otherwise print error of another
1080 * partition is mounted.
1081 */
1082 if (!m_option) {
1083 int ct = umount_partitions(device, M_option);
1084
1085 if (ct == 0 && mountpoint)
1086 umount_one(mountpoint); /* probably whole-device */
1087
1088 if (M_option) {
1089 if (ct == 1 && mountpoint)
1090 umount_one(mountpoint);
1091 else if (ct)
1092 errx(EXIT_FAILURE, _("error: %s: device in use"), device);
1093 }
1094 }
1095
1096 /* handle -c option */
1097 if (c_option) {
1098 verbose(_("%s: selecting CD-ROM disc #%ld"), device, c_arg);
1099 fd = open_device(device);
1100 changer_select(fd, c_arg);
1101 set_device_speed(device);
1102 return EXIT_SUCCESS;
1103 }
1104
1105 /* if user did not specify type of eject, try all four methods */
1106 if (r_option + s_option + f_option + q_option == 0)
1107 r_option = s_option = f_option = q_option = 1;
1108
1109 /* open device */
1110 fd = open_device(device);
1111
1112 /* try various methods of ejecting until it works */
1113 if (r_option) {
1114 verbose(_("%s: trying to eject using CD-ROM eject command"), device);
1115 worked = eject_cdrom(fd);
1116 verbose(worked ? _("CD-ROM eject command succeeded") :
1117 _("CD-ROM eject command failed"));
1118 }
1119
1120 if (s_option && !worked) {
1121 verbose(_("%s: trying to eject using SCSI commands"), device);
1122 worked = eject_scsi(fd);
1123 verbose(worked ? _("SCSI eject succeeded") :
1124 _("SCSI eject failed"));
1125 }
1126
1127 if (f_option && !worked) {
1128 verbose(_("%s: trying to eject using floppy eject command"), device);
1129 worked = eject_floppy(fd);
1130 verbose(worked ? _("floppy eject command succeeded") :
1131 _("floppy eject command failed"));
1132 }
1133
1134 if (q_option && !worked) {
1135 verbose(_("%s: trying to eject using tape offline command"), device);
1136 worked = eject_tape(fd);
1137 verbose(worked ? _("tape offline command succeeded") :
1138 _("tape offline command failed"));
1139 }
1140
1141 if (!worked)
1142 errx(EXIT_FAILURE, _("unable to eject"));
1143
1144 /* cleanup */
1145 close(fd);
1146 free(device);
1147 free(mountpoint);
1148
1149 mnt_free_table(mtab);
1150 mnt_free_cache(cache);
1151
1152 return EXIT_SUCCESS;
1153 }