]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/eject.c
eject: use sysfs API to detect hotplug
[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 #include "monotonic.h"
56
57 /*
58 * sg_io_hdr_t driver_status -- see kernel include/scsi/scsi.h
59 */
60 #ifndef DRIVER_SENSE
61 # define DRIVER_SENSE 0x08
62 #endif
63
64
65 #define EJECT_DEFAULT_DEVICE "/dev/cdrom"
66
67
68 /* Used by the toggle_tray() function. If ejecting the tray takes this
69 * time or less, the tray was probably already ejected, so we close it
70 * again.
71 */
72 #define TRAY_WAS_ALREADY_OPEN_USECS 200000 /* about 0.2 seconds */
73
74 struct eject_control {
75 struct libmnt_table *mtab;
76 char *device; /* device or mount point to be ejected */
77 int fd; /* file descriptor for device */
78 unsigned int /* command flags and arguments */
79 a_option:1,
80 c_option:1,
81 d_option:1,
82 F_option:1,
83 f_option:1,
84 i_option:1,
85 M_option:1,
86 m_option:1,
87 n_option:1,
88 p_option:1,
89 q_option:1,
90 r_option:1,
91 s_option:1,
92 T_option:1,
93 t_option:1,
94 v_option:1,
95 X_option:1,
96 x_option:1,
97 a_arg:1,
98 i_arg:1;
99 long int c_arg; /* changer slot number */
100 long int x_arg; /* cd speed */
101 };
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 struct eject_control *ctl, const char *fmt, ...)
111 {
112 va_list va;
113
114 if (!ctl->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(struct eject_control *ctl, int argc, char **argv)
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 ctl->a_option = 1;
203 if (!strcmp(optarg, "0") || !strcmp(optarg, "off"))
204 ctl->a_arg = 0;
205 else if (!strcmp(optarg, "1") || !strcmp(optarg, "on"))
206 ctl->a_arg = 1;
207 else
208 errx(EXIT_FAILURE, _("invalid argument to --auto/-a option"));
209 break;
210 case 'c':
211 ctl->c_option = 1;
212 ctl->c_arg = strtoul_or_err(optarg, _("invalid argument to --changerslot/-c option"));
213 break;
214 case 'x':
215 ctl->x_option = 1;
216 ctl->x_arg = strtoul_or_err(optarg, _("invalid argument to --cdspeed/-x option"));
217 break;
218 case 'd':
219 ctl->d_option = 1;
220 break;
221 case 'f':
222 ctl->f_option = 1;
223 break;
224 case 'F':
225 ctl->F_option = 1;
226 break;
227 case 'h':
228 usage(stdout);
229 break;
230 case 'i':
231 ctl->i_option = 1;
232 if (!strcmp(optarg, "0") || !strcmp(optarg, "off"))
233 ctl->i_arg = 0;
234 else if (!strcmp(optarg, "1") || !strcmp(optarg, "on"))
235 ctl->i_arg = 1;
236 else
237 errx(EXIT_FAILURE, _("invalid argument to --manualeject/-i option"));
238 break;
239 case 'm':
240 ctl->m_option = 1;
241 break;
242 case 'M':
243 ctl->M_option = 1;
244 break;
245 case 'n':
246 ctl->n_option = 1;
247 break;
248 case 'p':
249 ctl->p_option = 1;
250 break;
251 case 'q':
252 ctl->q_option = 1;
253 break;
254 case 'r':
255 ctl->r_option = 1;
256 break;
257 case 's':
258 ctl->s_option = 1;
259 break;
260 case 't':
261 ctl->t_option = 1;
262 break;
263 case 'T':
264 ctl->T_option = 1;
265 break;
266 case 'X':
267 ctl->X_option = 1;
268 break;
269 case 'v':
270 ctl->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 ctl->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(const struct eject_control *ctl)
320 {
321 int status = -1;
322
323 #if defined(CDROM_SET_OPTIONS) && defined(CDROM_CLEAR_OPTIONS)
324 if (ctl->a_arg)
325 status = ioctl(ctl->fd, CDROM_SET_OPTIONS, CDO_AUTO_EJECT);
326 else
327 status = ioctl(ctl->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(const struct eject_control *ctl)
347 {
348 if (ioctl(ctl->fd, CDROM_LOCKDOOR, ctl->i_arg) < 0)
349 err(EXIT_FAILURE, _("CD-ROM lock door command failed"));
350
351 if (ctl->i_arg)
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(const struct eject_control *ctl)
362 {
363 #ifdef CDROM_SELECT_DISC
364 if (ioctl(ctl->fd, CDROM_SELECT_DISC, ctl->c_arg) < 0)
365 err(EXIT_FAILURE, _("CD-ROM select disc command failed"));
366
367 #elif defined CDROMLOADFROMSLOT
368 if (ioctl(ctl->fd, CDROMLOADFROMSLOT, ctl->c_arg) != 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 int ret = ioctl(fd, CDROM_LOCKDOOR, 0);
402 if (ret < 0)
403 return 0;
404 return ioctl(fd, CDROMEJECT) >= 0;
405 #elif defined(CDIOCEJECT)
406 return ioctl(fd, CDIOCEJECT) >= 0;
407 #else
408 warnx(_("CD-ROM eject unsupported"));
409 errno = ENOSYS;
410 return 0;
411 #endif
412 }
413
414 /*
415 * Toggle tray.
416 *
417 * Written by Benjamin Schwenk <benjaminschwenk@yahoo.de> and
418 * Sybren Stuvel <sybren@thirdtower.com>
419 *
420 * Not supported by older kernels because it might use
421 * CloseTray().
422 *
423 */
424 static void toggle_tray(int fd)
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 #else
448 struct timeval time_start, time_stop;
449 int time_elapsed;
450
451 /* Try to open the CDROM tray and measure the time therefor
452 * needed. In my experience the function needs less than 0.05
453 * seconds if the tray was already open, and at least 1.5 seconds
454 * if it was closed. */
455 gettime_monotonic(&time_start);
456
457 /* Send the CDROMEJECT command to the device. */
458 if (!eject_cdrom(fd))
459 err(EXIT_FAILURE, _("CD-ROM eject command failed"));
460
461 /* Get the second timestamp, to measure the time needed to open
462 * the tray. */
463 gettime_monotonic(&time_stop);
464
465 time_elapsed = (time_stop.tv_sec * 1000000 + time_stop.tv_usec) -
466 (time_start.tv_sec * 1000000 + time_start.tv_usec);
467
468 /* If the tray "opened" too fast, we can be nearly sure, that it
469 * was already open. In this case, close it now. Else the tray was
470 * closed before. This would mean that we are done. */
471 if (time_elapsed < TRAY_WAS_ALREADY_OPEN_USECS)
472 close_tray(fd);
473 #endif
474 }
475
476 /*
477 * Select Speed of CD-ROM drive.
478 * Thanks to Roland Krivanek (krivanek@fmph.uniba.sk)
479 * http://dmpc.dbp.fmph.uniba.sk/~krivanek/cdrom_speed/
480 */
481 static void select_speed(const struct eject_control *ctl)
482 {
483 #ifdef CDROM_SELECT_SPEED
484 if (ioctl(ctl->fd, CDROM_SELECT_SPEED, ctl->x_arg) != 0)
485 err(EXIT_FAILURE, _("CD-ROM select speed command failed"));
486 #else
487 warnx(_("CD-ROM select speed command not supported by this kernel"));
488 #endif
489 }
490
491 /*
492 * Read Speed of CD-ROM drive. From Linux 2.6.13, the current speed
493 * is correctly reported
494 */
495 static int read_speed(const char *devname)
496 {
497 int drive_number = -1;
498 char *name;
499 FILE *f;
500
501 f = fopen(_PATH_PROC_CDROMINFO, "r");
502 if (!f)
503 err(EXIT_FAILURE, _("cannot open %s"), _PATH_PROC_CDROMINFO);
504
505 name = strrchr(devname, '/') + 1;
506
507 while (name && !feof(f)) {
508 char line[512];
509 char *str;
510
511 if (!fgets(line, sizeof(line), f))
512 break;
513
514 /* find drive number in line "drive name" */
515 if (drive_number == -1) {
516 if (strncmp(line, "drive name:", 11) == 0) {
517 str = strtok(&line[11], "\t ");
518 drive_number = 0;
519 while (str && strncmp(name, str, strlen(name)) != 0) {
520 drive_number++;
521 str = strtok(NULL, "\t ");
522 if (!str)
523 errx(EXIT_FAILURE,
524 _("%s: failed to finding CD-ROM name"),
525 _PATH_PROC_CDROMINFO);
526 }
527 }
528 /* find line "drive speed" and read the correct speed */
529 } else {
530 if (strncmp(line, "drive speed:", 12) == 0) {
531 int i;
532
533 str = strtok(&line[12], "\t ");
534 for (i = 1; i < drive_number; i++)
535 str = strtok(NULL, "\t ");
536
537 if (!str)
538 errx(EXIT_FAILURE,
539 _("%s: failed to read speed"),
540 _PATH_PROC_CDROMINFO);
541 fclose(f);
542 return atoi(str);
543 }
544 }
545 }
546
547 errx(EXIT_FAILURE, _("failed to read speed"));
548 }
549
550 /*
551 * List Speed of CD-ROM drive.
552 */
553 static void list_speeds(struct eject_control *ctl)
554 {
555 #ifdef CDROM_SELECT_SPEED
556 int max_speed, curr_speed = 0;
557
558 select_speed(ctl);
559 max_speed = read_speed(ctl->device);
560
561 while (curr_speed < max_speed) {
562 ctl->x_arg = curr_speed + 1;
563 select_speed(ctl);
564 curr_speed = read_speed(ctl->device);
565 if (ctl->x_arg < curr_speed)
566 printf("%d ", curr_speed);
567 else
568 curr_speed = ctl->x_arg + 1;
569 }
570
571 printf("\n");
572 #else
573 warnx(_("CD-ROM select speed command not supported by this kernel"));
574 #endif
575 }
576
577 /*
578 * Eject using SCSI SG_IO commands. Return 1 if successful, 0 otherwise.
579 */
580 static int eject_scsi(const struct eject_control *ctl)
581 {
582 int status, k;
583 sg_io_hdr_t io_hdr;
584 unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0};
585 unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0};
586 unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 2, 0};
587 unsigned char inqBuff[2];
588 unsigned char sense_buffer[32];
589
590 if ((ioctl(ctl->fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
591 verbose(ctl, _("not an sg device, or old sg driver"));
592 return 0;
593 }
594
595 memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
596 io_hdr.interface_id = 'S';
597 io_hdr.cmd_len = 6;
598 io_hdr.mx_sb_len = sizeof(sense_buffer);
599 io_hdr.dxfer_direction = SG_DXFER_NONE;
600 io_hdr.dxfer_len = 0;
601 io_hdr.dxferp = inqBuff;
602 io_hdr.sbp = sense_buffer;
603 io_hdr.timeout = 10000;
604
605 io_hdr.cmdp = allowRmBlk;
606 status = ioctl(ctl->fd, SG_IO, (void *)&io_hdr);
607 if (status < 0 || io_hdr.host_status || io_hdr.driver_status)
608 return 0;
609
610 io_hdr.cmdp = startStop1Blk;
611 status = ioctl(ctl->fd, SG_IO, (void *)&io_hdr);
612 if (status < 0 || io_hdr.host_status)
613 return 0;
614
615 /* Ignore errors when there is not medium -- in this case driver sense
616 * buffer sets MEDIUM NOT PRESENT (3a) bit. For more details see:
617 * http://www.tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/SCSI-Programming-HOWTO-22.html#sec-sensecodes
618 * -- kzak Jun 2013
619 */
620 if (io_hdr.driver_status != 0 &&
621 !(io_hdr.driver_status == DRIVER_SENSE && io_hdr.sbp &&
622 io_hdr.sbp[12] == 0x3a))
623 return 0;
624
625 io_hdr.cmdp = startStop2Blk;
626 status = ioctl(ctl->fd, SG_IO, (void *)&io_hdr);
627 if (status < 0 || io_hdr.host_status || io_hdr.driver_status)
628 return 0;
629
630 /* force kernel to reread partition table when new disc inserted */
631 ioctl(ctl->fd, BLKRRPART);
632 return 1;
633 }
634
635 /*
636 * Eject using FDEJECT ioctl. Return 1 if successful, 0 otherwise.
637 */
638 static int eject_floppy(int fd)
639 {
640 return ioctl(fd, FDEJECT) >= 0;
641 }
642
643
644 /*
645 * Rewind and eject using tape ioctl. Return 1 if successful, 0 otherwise.
646 */
647 static int eject_tape(int fd)
648 {
649 struct mtop op = { .mt_op = MTOFFL, .mt_count = 0 };
650
651 return ioctl(fd, MTIOCTOP, &op) >= 0;
652 }
653
654
655 /* umount a device. */
656 static void umount_one(const struct eject_control *ctl, const char *name)
657 {
658 int status;
659
660 if (!name)
661 return;
662
663 verbose(ctl, _("%s: unmounting"), name);
664
665 switch (fork()) {
666 case 0: /* child */
667 if (setgid(getgid()) < 0)
668 err(EXIT_FAILURE, _("cannot set group id"));
669
670 if (setuid(getuid()) < 0)
671 err(EXIT_FAILURE, _("cannot set user id"));
672
673 if (ctl->p_option)
674 execl("/bin/umount", "/bin/umount", name, "-n", NULL);
675 else
676 execl("/bin/umount", "/bin/umount", name, NULL);
677
678 errx(EXIT_FAILURE, _("unable to exec /bin/umount of `%s'"), name);
679
680 case -1:
681 warn( _("unable to fork"));
682 break;
683
684 default: /* parent */
685 wait(&status);
686 if (WIFEXITED(status) == 0)
687 errx(EXIT_FAILURE,
688 _("unmount of `%s' did not exit normally"), name);
689
690 if (WEXITSTATUS(status) != 0)
691 errx(EXIT_FAILURE, _("unmount of `%s' failed\n"), name);
692 break;
693 }
694 }
695
696 /* Open a device file. */
697 static void open_device(struct eject_control *ctl)
698 {
699 ctl->fd = open(ctl->device, O_RDWR | O_NONBLOCK);
700 if (ctl->fd < 0)
701 ctl->fd = open(ctl->device, O_RDONLY | O_NONBLOCK);
702 if (ctl->fd == -1)
703 err(EXIT_FAILURE, _("cannot open %s"), ctl->device);
704 }
705
706 /*
707 * See if device has been mounted by looking in mount table. If so, set
708 * device name and mount point name, and return 1, otherwise return 0.
709 */
710 static int device_get_mountpoint(struct eject_control *ctl, char **devname, char **mnt)
711 {
712 struct libmnt_fs *fs;
713 int rc;
714
715 *mnt = NULL;
716
717 if (!ctl->mtab) {
718 struct libmnt_cache *cache;
719
720 ctl->mtab = mnt_new_table();
721 if (!ctl->mtab)
722 err(EXIT_FAILURE, _("failed to initialize libmount table"));
723
724 cache = mnt_new_cache();
725 mnt_table_set_cache(ctl->mtab, cache);
726 mnt_unref_cache(cache);
727
728 if (ctl->p_option)
729 rc = mnt_table_parse_file(ctl->mtab, _PATH_PROC_MOUNTINFO);
730 else
731 rc = mnt_table_parse_mtab(ctl->mtab, NULL);
732 if (rc)
733 err(EXIT_FAILURE, _("failed to parse mount table"));
734 }
735
736 fs = mnt_table_find_source(ctl->mtab, *devname, MNT_ITER_BACKWARD);
737 if (!fs) {
738 /* maybe 'devname' is mountpoint rather than a real device */
739 fs = mnt_table_find_target(ctl->mtab, *devname, MNT_ITER_BACKWARD);
740 if (fs) {
741 free(*devname);
742 *devname = xstrdup(mnt_fs_get_source(fs));
743 }
744 }
745
746 if (fs)
747 *mnt = xstrdup(mnt_fs_get_target(fs));
748 return *mnt ? 0 : -1;
749 }
750
751 static char *get_disk_devname(const char *device)
752 {
753 struct stat st;
754 dev_t diskno = 0;
755 char diskname[128];
756
757 if (stat(device, &st) != 0)
758 return NULL;
759
760 /* get whole-disk devno */
761 if (sysfs_devno_to_wholedisk(st.st_rdev, diskname,
762 sizeof(diskname), &diskno) != 0)
763 return NULL;
764
765 return st.st_rdev == diskno ? NULL : find_device(diskname);
766 }
767
768 static int umount_partitions(struct eject_control *ctl)
769 {
770 struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY;
771 dev_t devno;
772 DIR *dir = NULL;
773 struct dirent *d;
774 int count = 0;
775
776 devno = sysfs_devname_to_devno(ctl->device, NULL);
777 if (sysfs_init(&cxt, devno, NULL) != 0)
778 return 0;
779
780 /* open /sys/block/<wholedisk> */
781 if (!(dir = sysfs_opendir(&cxt, NULL)))
782 goto done;
783
784 /* scan for partition subdirs */
785 while ((d = readdir(dir))) {
786 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
787 continue;
788
789 if (sysfs_is_partition_dirent(dir, d, ctl->device)) {
790 char *mnt = NULL;
791 char *dev = find_device(d->d_name);
792
793 if (dev && device_get_mountpoint(ctl, &dev, &mnt) == 0) {
794 verbose(ctl, _("%s: mounted on %s"), dev, mnt);
795 if (!ctl->M_option)
796 umount_one(ctl, mnt);
797 count++;
798 }
799 free(dev);
800 free(mnt);
801 }
802 }
803
804 done:
805 if (dir)
806 closedir(dir);
807 sysfs_deinit(&cxt);
808
809 return count;
810 }
811
812 static int is_hotpluggable(const struct eject_control *ctl)
813 {
814 struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY;
815 dev_t devno;
816 int rc = 0;
817
818 devno = sysfs_devname_to_devno(ctl->device, NULL);
819 if (sysfs_init(&cxt, devno, NULL) != 0)
820 return 0;
821
822 rc = sysfs_is_hotpluggable(&cxt);
823
824 sysfs_deinit(&cxt);
825 return rc;
826 }
827
828
829 /* handle -x option */
830 static void set_device_speed(struct eject_control *ctl)
831 {
832 if (!ctl->x_option)
833 return;
834
835 if (ctl->x_arg == 0)
836 verbose(ctl, _("setting CD-ROM speed to auto"));
837 else
838 verbose(ctl, _("setting CD-ROM speed to %ldX"), ctl->x_arg);
839
840 open_device(ctl);
841 select_speed(ctl);
842 exit(EXIT_SUCCESS);
843 }
844
845
846 /* main program */
847 int main(int argc, char **argv)
848 {
849 char *disk = NULL;
850 char *mountpoint = NULL;
851 int worked = 0; /* set to 1 when successfully ejected */
852 struct eject_control ctl = { 0 };
853
854 setlocale(LC_ALL,"");
855 bindtextdomain(PACKAGE, LOCALEDIR);
856 textdomain(PACKAGE);
857 atexit(close_stdout);
858
859 /* parse the command line arguments */
860 parse_args(&ctl, argc, argv);
861
862 /* handle -d option */
863 if (ctl.d_option) {
864 info(_("default device: `%s'"), EJECT_DEFAULT_DEVICE);
865 return EXIT_SUCCESS;
866 }
867
868 if (!ctl.device) {
869 ctl.device = mnt_resolve_path(EJECT_DEFAULT_DEVICE, NULL);
870 verbose(&ctl, _("using default device `%s'"), ctl.device);
871 } else {
872 char *p;
873
874 if (ctl.device[strlen(ctl.device) - 1] == '/')
875 ctl.device[strlen(ctl.device) - 1] = '\0';
876
877 /* figure out full device or mount point name */
878 p = find_device(ctl.device);
879 if (p)
880 free(ctl.device);
881 else
882 p = ctl.device;
883
884 ctl.device = mnt_resolve_spec(p, NULL);
885 free(p);
886 }
887
888 if (!ctl.device)
889 errx(EXIT_FAILURE, _("%s: unable to find device"), ctl.device);
890
891 verbose(&ctl, _("device name is `%s'"), ctl.device);
892
893 device_get_mountpoint(&ctl, &ctl.device, &mountpoint);
894 if (mountpoint)
895 verbose(&ctl, _("%s: mounted on %s"), ctl.device, mountpoint);
896 else
897 verbose(&ctl, _("%s: not mounted"), ctl.device);
898
899 disk = get_disk_devname(ctl.device);
900 if (disk) {
901 verbose(&ctl, _("%s: disc device: %s (disk device will be used for eject)"), ctl.device, disk);
902 free(ctl.device);
903 ctl.device = disk;
904 disk = NULL;
905 } else {
906 struct stat st;
907
908 if (stat(ctl.device, &st) != 0 || !S_ISBLK(st.st_mode))
909 errx(EXIT_FAILURE, _("%s: not found mountpoint or device "
910 "with the given name"), ctl.device);
911
912 verbose(&ctl, _("%s: is whole-disk device"), ctl.device);
913 }
914
915 if (ctl.F_option == 0 && is_hotpluggable(&ctl) == 0)
916 errx(EXIT_FAILURE, _("%s: is not hot-pluggable device"), ctl.device);
917
918 /* handle -n option */
919 if (ctl.n_option) {
920 info(_("device is `%s'"), ctl.device);
921 verbose(&ctl, _("exiting due to -n/--noop option"));
922 return EXIT_SUCCESS;
923 }
924
925 /* handle -i option */
926 if (ctl.i_option) {
927 open_device(&ctl);
928 manual_eject(&ctl);
929 return EXIT_SUCCESS;
930 }
931
932 /* handle -a option */
933 if (ctl.a_option) {
934 if (ctl.a_arg)
935 verbose(&ctl, _("%s: enabling auto-eject mode"), ctl.device);
936 else
937 verbose(&ctl, _("%s: disabling auto-eject mode"), ctl.device);
938 open_device(&ctl);
939 auto_eject(&ctl);
940 return EXIT_SUCCESS;
941 }
942
943 /* handle -t option */
944 if (ctl.t_option) {
945 verbose(&ctl, _("%s: closing tray"), ctl.device);
946 open_device(&ctl);
947 close_tray(ctl.fd);
948 set_device_speed(&ctl);
949 return EXIT_SUCCESS;
950 }
951
952 /* handle -T option */
953 if (ctl.T_option) {
954 verbose(&ctl, _("%s: toggling tray"), ctl.device);
955 open_device(&ctl);
956 toggle_tray(ctl.fd);
957 set_device_speed(&ctl);
958 return EXIT_SUCCESS;
959 }
960
961 /* handle -X option */
962 if (ctl.X_option) {
963 verbose(&ctl, _("%s: listing CD-ROM speed"), ctl.device);
964 open_device(&ctl);
965 list_speeds(&ctl);
966 return EXIT_SUCCESS;
967 }
968
969 /* handle -x option only */
970 if (!ctl.c_option)
971 set_device_speed(&ctl);
972
973
974 /*
975 * Unmount all partitions if -m is not specified; or umount given
976 * mountpoint if -M is specified, otherwise print error of another
977 * partition is mounted.
978 */
979 if (!ctl.m_option) {
980 int ct = umount_partitions(&ctl);
981
982 if (ct == 0 && mountpoint)
983 umount_one(&ctl, mountpoint); /* probably whole-device */
984
985 if (ctl.M_option) {
986 if (ct == 1 && mountpoint)
987 umount_one(&ctl, mountpoint);
988 else if (ct)
989 errx(EXIT_FAILURE, _("error: %s: device in use"), ctl.device);
990 }
991 }
992
993 /* handle -c option */
994 if (ctl.c_option) {
995 verbose(&ctl, _("%s: selecting CD-ROM disc #%ld"), ctl.device, ctl.c_arg);
996 open_device(&ctl);
997 changer_select(&ctl);
998 set_device_speed(&ctl);
999 return EXIT_SUCCESS;
1000 }
1001
1002 /* if user did not specify type of eject, try all four methods */
1003 if (ctl.r_option + ctl.s_option + ctl.f_option + ctl.q_option == 0)
1004 ctl.r_option = ctl.s_option = ctl.f_option = ctl.q_option = 1;
1005
1006 /* open device */
1007 open_device(&ctl);
1008
1009 /* try various methods of ejecting until it works */
1010 if (ctl.r_option) {
1011 verbose(&ctl, _("%s: trying to eject using CD-ROM eject command"), ctl.device);
1012 worked = eject_cdrom(ctl.fd);
1013 verbose(&ctl, worked ? _("CD-ROM eject command succeeded") :
1014 _("CD-ROM eject command failed"));
1015 }
1016
1017 if (ctl.s_option && !worked) {
1018 verbose(&ctl, _("%s: trying to eject using SCSI commands"), ctl.device);
1019 worked = eject_scsi(&ctl);
1020 verbose(&ctl, worked ? _("SCSI eject succeeded") :
1021 _("SCSI eject failed"));
1022 }
1023
1024 if (ctl.f_option && !worked) {
1025 verbose(&ctl, _("%s: trying to eject using floppy eject command"), ctl.device);
1026 worked = eject_floppy(ctl.fd);
1027 verbose(&ctl, worked ? _("floppy eject command succeeded") :
1028 _("floppy eject command failed"));
1029 }
1030
1031 if (ctl.q_option && !worked) {
1032 verbose(&ctl, _("%s: trying to eject using tape offline command"), ctl.device);
1033 worked = eject_tape(ctl.fd);
1034 verbose(&ctl, worked ? _("tape offline command succeeded") :
1035 _("tape offline command failed"));
1036 }
1037
1038 if (!worked)
1039 errx(EXIT_FAILURE, _("unable to eject"));
1040
1041 /* cleanup */
1042 close(ctl.fd);
1043 free(ctl.device);
1044 free(mountpoint);
1045
1046 mnt_unref_table(ctl.mtab);
1047
1048 return EXIT_SUCCESS;
1049 }