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