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