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