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