]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/eject.c
Merge branch 'patch-23' of https://github.com/mariobl/util-linux
[thirdparty/util-linux.git] / sys-utils / eject.c
1 /*
2 * Copyright (C) 1994-2005 Jeff Tranter (tranter@pobox.com)
3 * Copyright (C) 2012 Karel Zak <kzak@redhat.com>
4 * Copyright (C) Michal Luscon <mluscon@redhat.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <err.h>
28 #include <stdarg.h>
29
30 #include <getopt.h>
31 #include <errno.h>
32 #include <regex.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/ioctl.h>
36 #include <sys/wait.h>
37 #include <sys/mtio.h>
38 #include <linux/cdrom.h>
39 #include <linux/fd.h>
40 #include <sys/mount.h>
41 #include <scsi/scsi.h>
42 #include <scsi/sg.h>
43 #include <scsi/scsi_ioctl.h>
44 #include <sys/time.h>
45
46 #include <libmount.h>
47
48 #include "c.h"
49 #include "closestream.h"
50 #include "nls.h"
51 #include "strutils.h"
52 #include "xalloc.h"
53 #include "pathnames.h"
54 #include "sysfs.h"
55 #include "monotonic.h"
56
57 /*
58 * sg_io_hdr_t driver_status -- see kernel include/scsi/sg.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
100 unsigned int force_exclusive; /* use O_EXCL */
101
102 long int c_arg; /* changer slot number */
103 long int x_arg; /* cd speed */
104 };
105
106 static void vinfo(const char *fmt, va_list va)
107 {
108 fprintf(stdout, "%s: ", program_invocation_short_name);
109 vprintf(fmt, va);
110 fputc('\n', stdout);
111 }
112
113 static inline void __attribute__ ((__format__ (__printf__, 2, 3)))
114 verbose(const struct eject_control *ctl, const char *fmt, ...)
115 {
116 va_list va;
117
118 if (!ctl->v_option)
119 return;
120
121 va_start(va, fmt);
122 vinfo(fmt, va);
123 va_end(va);
124 }
125
126 static inline __attribute__ ((__format__ (__printf__, 1, 2)))
127 void info(const char *fmt, ...)
128 {
129 va_list va;
130 va_start(va, fmt);
131 vinfo(fmt, va);
132 va_end(va);
133 }
134
135 static void __attribute__((__noreturn__)) usage(void)
136 {
137 FILE *out = stdout;
138 fputs(USAGE_HEADER, out);
139 fprintf(out,
140 _(" %s [options] [<device>|<mountpoint>]\n"), program_invocation_short_name);
141
142 fputs(USAGE_SEPARATOR, out);
143 fputs(_("Eject removable media.\n"), out);
144
145 fputs(USAGE_OPTIONS, out);
146 fputs(_(" -a, --auto <on|off> turn auto-eject feature on or off\n"
147 " -c, --changerslot <slot> switch discs on a CD-ROM changer\n"
148 " -d, --default display default device\n"
149 " -f, --floppy eject floppy\n"
150 " -F, --force don't care about device type\n"
151 " -i, --manualeject <on|off> toggle manual eject protection on/off\n"
152 " -m, --no-unmount do not unmount device even if it is mounted\n"
153 " -M, --no-partitions-unmount do not unmount another partitions\n"
154 " -n, --noop don't eject, just show device found\n"
155 " -p, --proc use /proc/mounts instead of /etc/mtab\n"
156 " -q, --tape eject tape\n"
157 " -r, --cdrom eject CD-ROM\n"
158 " -s, --scsi eject SCSI device\n"
159 " -t, --trayclose close tray\n"
160 " -T, --traytoggle toggle tray\n"
161 " -v, --verbose enable verbose output\n"
162 " -x, --cdspeed <speed> set CD-ROM max speed\n"
163 " -X, --listspeed list CD-ROM available speeds\n"),
164 out);
165
166 fputs(USAGE_SEPARATOR, out);
167 fprintf(out, USAGE_HELP_OPTIONS(29));
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(EXIT_SUCCESS);
173 }
174
175
176 /* Handle command line options. */
177 static void parse_args(struct eject_control *ctl, int argc, char **argv)
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 {NULL, 0, NULL, 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 ctl->a_option = 1;
210 ctl->a_arg = parse_switch(optarg, _("argument error"),
211 "on", "off", "1", "0", NULL);
212 break;
213 case 'c':
214 ctl->c_option = 1;
215 ctl->c_arg = strtoul_or_err(optarg, _("invalid argument to --changerslot/-c option"));
216 break;
217 case 'x':
218 ctl->x_option = 1;
219 ctl->x_arg = strtoul_or_err(optarg, _("invalid argument to --cdspeed/-x option"));
220 break;
221 case 'd':
222 ctl->d_option = 1;
223 break;
224 case 'f':
225 ctl->f_option = 1;
226 break;
227 case 'F':
228 ctl->F_option = 1;
229 break;
230 case 'i':
231 ctl->i_option = 1;
232 ctl->i_arg = parse_switch(optarg, _("argument error"),
233 "on", "off", "1", "0", NULL);
234 break;
235 case 'm':
236 ctl->m_option = 1;
237 break;
238 case 'M':
239 ctl->M_option = 1;
240 break;
241 case 'n':
242 ctl->n_option = 1;
243 break;
244 case 'p':
245 ctl->p_option = 1;
246 break;
247 case 'q':
248 ctl->q_option = 1;
249 break;
250 case 'r':
251 ctl->r_option = 1;
252 break;
253 case 's':
254 ctl->s_option = 1;
255 break;
256 case 't':
257 ctl->t_option = 1;
258 break;
259 case 'T':
260 ctl->T_option = 1;
261 break;
262 case 'X':
263 ctl->X_option = 1;
264 break;
265 case 'v':
266 ctl->v_option = 1;
267 break;
268
269 case 'h':
270 usage();
271 case 'V':
272 print_version(EXIT_SUCCESS);
273 default:
274 errtryhelp(EXIT_FAILURE);
275 break;
276 }
277 }
278
279 /* check for a single additional argument */
280 if ((argc - optind) > 1)
281 errx(EXIT_FAILURE, _("too many arguments"));
282
283 if ((argc - optind) == 1)
284 ctl->device = xstrdup(argv[optind]);
285 }
286
287 /*
288 * Given name, such as foo, see if any of the following exist:
289 *
290 * foo (if foo starts with '.' or '/')
291 * /dev/foo
292 *
293 * If found, return the full path. If not found, return 0.
294 * Returns pointer to dynamically allocated string.
295 */
296 static char *find_device(const char *name)
297 {
298 if (!name)
299 return NULL;
300
301 if ((*name == '.' || *name == '/') && access(name, F_OK) == 0)
302 return xstrdup(name);
303
304 char buf[PATH_MAX];
305
306 snprintf(buf, sizeof(buf), "/dev/%s", name);
307 if (access(buf, F_OK) == 0)
308 return xstrdup(buf);
309
310 return NULL;
311 }
312
313 /* Set or clear auto-eject mode. */
314 static void auto_eject(const struct eject_control *ctl)
315 {
316 int status = -1;
317
318 #if defined(CDROM_SET_OPTIONS) && defined(CDROM_CLEAR_OPTIONS)
319 if (ctl->a_arg)
320 status = ioctl(ctl->fd, CDROM_SET_OPTIONS, CDO_AUTO_EJECT);
321 else
322 status = ioctl(ctl->fd, CDROM_CLEAR_OPTIONS, CDO_AUTO_EJECT);
323 #else
324 errno = ENOSYS;
325 #endif
326 if (status < 0)
327 err(EXIT_FAILURE,_("CD-ROM auto-eject command failed"));
328 }
329
330 /*
331 * Stops CDROM from opening on manual eject button press.
332 * This can be useful when you carry your laptop
333 * in your bag while it's on and no CD inserted in it's drive.
334 * Implemented as found in Documentation/userspace-api/ioctl/cdrom.rst
335 */
336 static void manual_eject(const struct eject_control *ctl)
337 {
338 if (ioctl(ctl->fd, CDROM_LOCKDOOR, ctl->i_arg) < 0) {
339 switch (errno) {
340 case EDRIVE_CANT_DO_THIS:
341 errx(EXIT_FAILURE, _("CD-ROM door lock is not supported"));
342 case EBUSY:
343 errx(EXIT_FAILURE, _("other users have the drive open and not CAP_SYS_ADMIN"));
344 default:
345 err(EXIT_FAILURE, _("CD-ROM lock door command failed"));
346 }
347 }
348
349 if (ctl->i_arg)
350 info(_("CD-Drive may NOT be ejected with device button"));
351 else
352 info(_("CD-Drive may be ejected with device button"));
353 }
354
355 /*
356 * Changer select. CDROM_SELECT_DISC is preferred, older kernels used
357 * CDROMLOADFROMSLOT.
358 */
359 static void changer_select(const struct eject_control *ctl)
360 {
361 #ifdef CDROM_SELECT_DISC
362 if (ioctl(ctl->fd, CDROM_SELECT_DISC, ctl->c_arg) < 0)
363 err(EXIT_FAILURE, _("CD-ROM select disc command failed"));
364
365 #elif defined CDROMLOADFROMSLOT
366 if (ioctl(ctl->fd, CDROMLOADFROMSLOT, ctl->c_arg) != 0)
367 err(EXIT_FAILURE, _("CD-ROM load from slot command failed"));
368 #else
369 warnx(_("IDE/ATAPI CD-ROM changer not supported by this kernel\n") );
370 #endif
371 }
372
373 /*
374 * Close tray. Not supported by older kernels.
375 */
376 static void close_tray(int fd)
377 {
378 int status;
379
380 #if defined(CDROMCLOSETRAY) || defined(CDIOCCLOSE)
381 #if defined(CDROMCLOSETRAY)
382 status = ioctl(fd, CDROMCLOSETRAY);
383 #elif defined(CDIOCCLOSE)
384 status = ioctl(fd, CDIOCCLOSE);
385 #endif
386 if (status != 0)
387 err(EXIT_FAILURE, _("CD-ROM tray close command failed"));
388 #else
389 warnx(_("CD-ROM tray close command not supported by this kernel\n"));
390 #endif
391 }
392
393 /*
394 * Eject using CDROMEJECT ioctl.
395 */
396 static int eject_cdrom(int fd)
397 {
398 #if defined(CDROMEJECT)
399 int ret = ioctl(fd, CDROM_LOCKDOOR, 0);
400 if (ret < 0)
401 return 0;
402 return ioctl(fd, CDROMEJECT) >= 0;
403 #elif defined(CDIOCEJECT)
404 return ioctl(fd, CDIOCEJECT) >= 0;
405 #else
406 warnx(_("CD-ROM eject unsupported"));
407 errno = ENOSYS;
408 return 0;
409 #endif
410 }
411
412 /*
413 * Toggle tray.
414 *
415 * Written by Benjamin Schwenk <benjaminschwenk@yahoo.de> and
416 * Sybren Stuvel <sybren@thirdtower.com>
417 *
418 * Not supported by older kernels because it might use
419 * CloseTray().
420 *
421 */
422 static void toggle_tray(int fd)
423 {
424 #ifdef CDROM_DRIVE_STATUS
425 /* First ask the CDROM for info, otherwise fall back to manual. */
426 switch (ioctl(fd, CDROM_DRIVE_STATUS)) {
427 case CDS_TRAY_OPEN:
428 close_tray(fd);
429 return;
430
431 case CDS_NO_DISC:
432 case CDS_DISC_OK:
433 if (!eject_cdrom(fd))
434 err(EXIT_FAILURE, _("CD-ROM eject command failed"));
435 return;
436 case CDS_NO_INFO:
437 warnx(_("no CD-ROM information available"));
438 return;
439 case CDS_DRIVE_NOT_READY:
440 warnx(_("CD-ROM drive is not ready"));
441 return;
442 default:
443 err(EXIT_FAILURE, _("CD-ROM status command failed"));
444 }
445 #else
446 struct timeval time_start, time_stop;
447 int time_elapsed;
448
449 /* Try to open the CDROM tray and measure the time therefore
450 * needed. In my experience the function needs less than 0.05
451 * seconds if the tray was already open, and at least 1.5 seconds
452 * if it was closed. */
453 gettime_monotonic(&time_start);
454
455 /* Send the CDROMEJECT command to the device. */
456 if (!eject_cdrom(fd))
457 err(EXIT_FAILURE, _("CD-ROM eject command failed"));
458
459 /* Get the second timestamp, to measure the time needed to open
460 * the tray. */
461 gettime_monotonic(&time_stop);
462
463 time_elapsed = (time_stop.tv_sec * 1000000 + time_stop.tv_usec) -
464 (time_start.tv_sec * 1000000 + time_start.tv_usec);
465
466 /* If the tray "opened" too fast, we can be nearly sure, that it
467 * was already open. In this case, close it now. Else the tray was
468 * closed before. This would mean that we are done. */
469 if (time_elapsed < TRAY_WAS_ALREADY_OPEN_USECS)
470 close_tray(fd);
471 #endif
472 }
473
474 /*
475 * Select Speed of CD-ROM drive.
476 * Thanks to Roland Krivanek (krivanek@fmph.uniba.sk)
477 * http://dmpc.dbp.fmph.uniba.sk/~krivanek/cdrom_speed/
478 */
479 static void select_speed(const struct eject_control *ctl)
480 {
481 #ifdef CDROM_SELECT_SPEED
482 if (ioctl(ctl->fd, CDROM_SELECT_SPEED, ctl->x_arg) != 0)
483 err(EXIT_FAILURE, _("CD-ROM select speed command failed"));
484 #else
485 warnx(_("CD-ROM select speed command not supported by this kernel"));
486 #endif
487 }
488
489 /*
490 * Read Speed of CD-ROM drive. From Linux 2.6.13, the current speed
491 * is correctly reported
492 */
493 static int read_speed(const char *devname)
494 {
495 int drive_number = -1;
496 char *name;
497 FILE *f;
498
499 f = fopen(_PATH_PROC_CDROMINFO, "r");
500 if (!f)
501 err(EXIT_FAILURE, _("cannot open %s"), _PATH_PROC_CDROMINFO);
502
503 name = strrchr(devname, '/') + 1;
504
505 while (name && !feof(f)) {
506 char line[512];
507 char *str;
508
509 if (!fgets(line, sizeof(line), f))
510 break;
511
512 /* find drive number in line "drive name" */
513 if (drive_number == -1) {
514 if (strncmp(line, "drive name:", 11) == 0) {
515 str = strtok(&line[11], "\t ");
516 drive_number = 0;
517 while (str && strncmp(name, str, strlen(name)) != 0) {
518 drive_number++;
519 str = strtok(NULL, "\t ");
520 if (!str)
521 errx(EXIT_FAILURE,
522 _("%s: failed to finding CD-ROM name"),
523 _PATH_PROC_CDROMINFO);
524 }
525 }
526 /* find line "drive speed" and read the correct speed */
527 } else {
528 if (strncmp(line, "drive speed:", 12) == 0) {
529 int n;
530
531 fclose(f);
532
533 str = line + 12;
534 normalize_whitespace((unsigned char *) str);
535
536 if (ul_strtos32(str, &n, 10) == 0)
537 return n;
538
539 errx(EXIT_FAILURE, _("%s: failed to read speed"),
540 _PATH_PROC_CDROMINFO);
541 }
542 }
543 }
544
545 errx(EXIT_FAILURE, _("failed to read speed"));
546 }
547
548 /*
549 * List Speed of CD-ROM drive.
550 */
551 static void list_speeds(struct eject_control *ctl)
552 {
553 int max_speed, curr_speed = 0;
554
555 select_speed(ctl);
556 max_speed = read_speed(ctl->device);
557
558 while (curr_speed < max_speed) {
559 ctl->x_arg = curr_speed + 1;
560 select_speed(ctl);
561 curr_speed = read_speed(ctl->device);
562 if (ctl->x_arg < curr_speed)
563 printf("%d ", curr_speed);
564 else
565 curr_speed = ctl->x_arg + 1;
566 }
567
568 printf("\n");
569 }
570
571 /*
572 * Eject using SCSI SG_IO commands. Return 1 if successful, 0 otherwise.
573 */
574 static int eject_scsi(const struct eject_control *ctl)
575 {
576 int status, k;
577 sg_io_hdr_t io_hdr;
578 unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0};
579 unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0};
580 unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 2, 0};
581 unsigned char inqBuff[2];
582 unsigned char sense_buffer[32];
583
584 if ((ioctl(ctl->fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
585 verbose(ctl, _("not an sg device, or old sg driver"));
586 return 0;
587 }
588
589 memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
590 io_hdr.interface_id = 'S';
591 io_hdr.cmd_len = 6;
592 io_hdr.mx_sb_len = sizeof(sense_buffer);
593 io_hdr.dxfer_direction = SG_DXFER_NONE;
594 io_hdr.dxfer_len = 0;
595 io_hdr.dxferp = inqBuff;
596 io_hdr.sbp = sense_buffer;
597 io_hdr.timeout = 10000;
598
599 io_hdr.cmdp = allowRmBlk;
600 status = ioctl(ctl->fd, SG_IO, (void *)&io_hdr);
601 if (status < 0 || io_hdr.host_status || io_hdr.driver_status)
602 return 0;
603
604 io_hdr.cmdp = startStop1Blk;
605 status = ioctl(ctl->fd, SG_IO, (void *)&io_hdr);
606 if (status < 0 || io_hdr.host_status)
607 return 0;
608
609 /* Ignore errors when there is not medium -- in this case driver sense
610 * buffer sets MEDIUM NOT PRESENT (3a) bit. For more details see:
611 * http://www.tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/SCSI-Programming-HOWTO-22.html#sec-sensecodes
612 * -- kzak Jun 2013
613 */
614 if (io_hdr.driver_status != 0 &&
615 !(io_hdr.driver_status == DRIVER_SENSE && io_hdr.sbp &&
616 io_hdr.sbp[12] == 0x3a))
617 return 0;
618
619 io_hdr.cmdp = startStop2Blk;
620 status = ioctl(ctl->fd, SG_IO, (void *)&io_hdr);
621 if (status < 0 || io_hdr.host_status || io_hdr.driver_status)
622 return 0;
623
624 /* force kernel to reread partition table when new disc inserted */
625 ioctl(ctl->fd, BLKRRPART);
626 return 1;
627 }
628
629 /*
630 * Eject using FDEJECT ioctl. Return 1 if successful, 0 otherwise.
631 */
632 static int eject_floppy(int fd)
633 {
634 return ioctl(fd, FDEJECT) >= 0;
635 }
636
637
638 /*
639 * Rewind and eject using tape ioctl. Return 1 if successful, 0 otherwise.
640 */
641 static int eject_tape(int fd)
642 {
643 struct mtop op = { .mt_op = MTOFFL, .mt_count = 0 };
644
645 return ioctl(fd, MTIOCTOP, &op) >= 0;
646 }
647
648
649 /* umount a device. */
650 static void umount_one(const struct eject_control *ctl, const char *name)
651 {
652 int status;
653
654 if (!name)
655 return;
656
657 verbose(ctl, _("%s: unmounting"), name);
658
659 switch (fork()) {
660 case 0: /* child */
661 if (drop_permissions() != 0)
662 err(EXIT_FAILURE, _("drop permissions failed"));
663 if (ctl->p_option)
664 execl("/bin/umount", "/bin/umount", name, "-n", (char *)NULL);
665 else
666 execl("/bin/umount", "/bin/umount", name, (char *)NULL);
667
668 errexec("/bin/umount");
669
670 case -1:
671 warn( _("unable to fork"));
672 break;
673
674 default: /* parent */
675 wait(&status);
676 if (WIFEXITED(status) == 0)
677 errx(EXIT_FAILURE,
678 _("unmount of `%s' did not exit normally"), name);
679
680 if (WEXITSTATUS(status) != 0)
681 errx(EXIT_FAILURE, _("unmount of `%s' failed\n"), name);
682 break;
683 }
684 }
685
686 /* Open a device file. */
687 static void open_device(struct eject_control *ctl)
688 {
689 int extra = ctl->F_option == 0 && /* never use O_EXCL on --force */
690 ctl->force_exclusive ? O_EXCL : 0;
691
692 ctl->fd = open(ctl->device, O_RDWR | O_NONBLOCK | extra);
693 if (ctl->fd < 0)
694 ctl->fd = open(ctl->device, O_RDONLY | O_NONBLOCK | extra);
695 if (ctl->fd == -1)
696 err(EXIT_FAILURE, _("cannot open %s"), ctl->device);
697 }
698
699 /*
700 * See if device has been mounted by looking in mount table. If so, set
701 * device name and mount point name, and return 1, otherwise return 0.
702 */
703 static int device_get_mountpoint(struct eject_control *ctl, char **devname, char **mnt)
704 {
705 struct libmnt_fs *fs;
706 int rc;
707
708 *mnt = NULL;
709
710 if (!ctl->mtab) {
711 struct libmnt_cache *cache;
712
713 ctl->mtab = mnt_new_table();
714 if (!ctl->mtab)
715 err(EXIT_FAILURE, _("failed to initialize libmount table"));
716
717 cache = mnt_new_cache();
718 mnt_table_set_cache(ctl->mtab, cache);
719 mnt_unref_cache(cache);
720
721 if (ctl->p_option)
722 rc = mnt_table_parse_file(ctl->mtab, _PATH_PROC_MOUNTINFO);
723 else
724 rc = mnt_table_parse_mtab(ctl->mtab, NULL);
725 if (rc)
726 err(EXIT_FAILURE, _("failed to parse mount table"));
727 }
728
729 fs = mnt_table_find_source(ctl->mtab, *devname, MNT_ITER_BACKWARD);
730 if (!fs) {
731 /* maybe 'devname' is mountpoint rather than a real device */
732 fs = mnt_table_find_target(ctl->mtab, *devname, MNT_ITER_BACKWARD);
733 if (fs) {
734 free(*devname);
735 *devname = xstrdup(mnt_fs_get_source(fs));
736 }
737 }
738
739 if (fs)
740 *mnt = xstrdup(mnt_fs_get_target(fs));
741 return *mnt ? 0 : -1;
742 }
743
744 static char *get_disk_devname(const char *device)
745 {
746 struct stat st;
747 dev_t diskno = 0;
748 char diskname[128];
749
750 if (stat(device, &st) != 0)
751 return NULL;
752
753 /* get whole-disk devno */
754 if (sysfs_devno_to_wholedisk(st.st_rdev, diskname,
755 sizeof(diskname), &diskno) != 0)
756 return NULL;
757
758 return st.st_rdev == diskno ? NULL : find_device(diskname);
759 }
760
761 /* umount all partitions if -M not specified, otherwise returns
762 * number of the mounted partitions only.
763 */
764 static int umount_partitions(struct eject_control *ctl)
765 {
766 struct path_cxt *pc = NULL;
767 dev_t devno;
768 DIR *dir = NULL;
769 struct dirent *d;
770 int count = 0;
771
772 devno = sysfs_devname_to_devno(ctl->device);
773 if (devno)
774 pc = ul_new_sysfs_path(devno, NULL, NULL);
775 if (!pc)
776 return 0;
777
778 /* open /sys/block/<wholedisk> */
779 if (!(dir = ul_path_opendir(pc, NULL)))
780 goto done;
781
782 /* scan for partition subdirs */
783 while ((d = readdir(dir))) {
784 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
785 continue;
786
787 if (sysfs_blkdev_is_partition_dirent(dir, d, ctl->device)) {
788 char *mnt = NULL;
789 char *dev = find_device(d->d_name);
790
791 if (dev && device_get_mountpoint(ctl, &dev, &mnt) == 0) {
792 verbose(ctl, _("%s: mounted on %s"), dev, mnt);
793 if (!ctl->M_option)
794 umount_one(ctl, mnt);
795 count++;
796 }
797 free(dev);
798 free(mnt);
799 }
800 }
801
802 done:
803 if (dir)
804 closedir(dir);
805 ul_unref_path(pc);
806
807 return count;
808 }
809
810 static int is_ejectable(const struct eject_control *ctl)
811 {
812 struct path_cxt *pc = NULL;
813 dev_t devno;
814 int rc = 0;
815
816 devno = sysfs_devname_to_devno(ctl->device);
817 if (devno)
818 pc = ul_new_sysfs_path(devno, NULL, NULL);
819 if (!pc)
820 return 0;
821
822 rc = sysfs_blkdev_is_hotpluggable(pc) || sysfs_blkdev_is_removable(pc);
823 ul_unref_path(pc);
824 return rc;
825 }
826
827
828 /* handle -x option */
829 static void set_device_speed(struct eject_control *ctl)
830 {
831 if (!ctl->x_option)
832 return;
833
834 if (ctl->x_arg == 0)
835 verbose(ctl, _("setting CD-ROM speed to auto"));
836 else
837 verbose(ctl, _("setting CD-ROM speed to %ldX"), ctl->x_arg);
838
839 open_device(ctl);
840 select_speed(ctl);
841 exit(EXIT_SUCCESS);
842 }
843
844
845 /* main program */
846 int main(int argc, char **argv)
847 {
848 char *disk = NULL;
849 char *mountpoint = NULL;
850 int worked = 0; /* set to 1 when successfully ejected */
851 struct eject_control ctl = { .fd = -1 };
852
853 setlocale(LC_ALL,"");
854 bindtextdomain(PACKAGE, LOCALEDIR);
855 textdomain(PACKAGE);
856 close_stdout_atexit();
857
858 /* parse the command line arguments */
859 parse_args(&ctl, argc, argv);
860
861 /* handle -d option */
862 if (ctl.d_option) {
863 info(_("default device: `%s'"), EJECT_DEFAULT_DEVICE);
864 return EXIT_SUCCESS;
865 }
866
867 if (!ctl.device) {
868 ctl.device = mnt_resolve_path(EJECT_DEFAULT_DEVICE, NULL);
869 verbose(&ctl, _("using default device `%s'"), ctl.device);
870 } else {
871 char *p;
872
873 if (ctl.device[strlen(ctl.device) - 1] == '/')
874 ctl.device[strlen(ctl.device) - 1] = '\0';
875
876 /* figure out full device or mount point name */
877 p = find_device(ctl.device);
878 if (p)
879 free(ctl.device);
880 else
881 p = ctl.device;
882
883 ctl.device = mnt_resolve_spec(p, NULL);
884 free(p);
885 }
886
887 if (!ctl.device)
888 errx(EXIT_FAILURE, _("unable to find device"));
889
890 verbose(&ctl, _("device name is `%s'"), ctl.device);
891
892 device_get_mountpoint(&ctl, &ctl.device, &mountpoint);
893 if (mountpoint)
894 verbose(&ctl, _("%s: mounted on %s"), ctl.device, mountpoint);
895 else
896 verbose(&ctl, _("%s: not mounted"), ctl.device);
897
898 disk = get_disk_devname(ctl.device);
899 if (disk) {
900 verbose(&ctl, _("%s: disc device: %s (disk device will be used for eject)"), ctl.device, disk);
901 free(ctl.device);
902 ctl.device = disk;
903 disk = NULL;
904 } else {
905 struct stat st;
906
907 if (stat(ctl.device, &st) != 0 || !S_ISBLK(st.st_mode))
908 errx(EXIT_FAILURE, _("%s: not found mountpoint or device "
909 "with the given name"), ctl.device);
910
911 verbose(&ctl, _("%s: is whole-disk device"), ctl.device);
912 }
913
914 if (ctl.F_option == 0 && is_ejectable(&ctl) == 0)
915 errx(EXIT_FAILURE, _("%s: is not ejectable device"), ctl.device);
916
917 /* handle -n option */
918 if (ctl.n_option) {
919 info(_("device is `%s'"), ctl.device);
920 verbose(&ctl, _("exiting due to -n/--noop option"));
921 goto done;
922 }
923
924 /* handle -i option */
925 if (ctl.i_option) {
926 open_device(&ctl);
927 manual_eject(&ctl);
928 goto done;
929 }
930
931 /* handle -a option */
932 if (ctl.a_option) {
933 if (ctl.a_arg)
934 verbose(&ctl, _("%s: enabling auto-eject mode"), ctl.device);
935 else
936 verbose(&ctl, _("%s: disabling auto-eject mode"), ctl.device);
937 open_device(&ctl);
938 auto_eject(&ctl);
939 goto done;
940 }
941
942 /* handle -t option */
943 if (ctl.t_option) {
944 verbose(&ctl, _("%s: closing tray"), ctl.device);
945 open_device(&ctl);
946 close_tray(ctl.fd);
947 set_device_speed(&ctl);
948 goto done;
949 }
950
951 /* handle -T option */
952 if (ctl.T_option) {
953 verbose(&ctl, _("%s: toggling tray"), ctl.device);
954 open_device(&ctl);
955 toggle_tray(ctl.fd);
956 set_device_speed(&ctl);
957 goto done;
958 }
959
960 /* handle -X option */
961 if (ctl.X_option) {
962 verbose(&ctl, _("%s: listing CD-ROM speed"), ctl.device);
963 open_device(&ctl);
964 list_speeds(&ctl);
965 goto done;
966 }
967
968 /* handle -x option only */
969 if (!ctl.c_option)
970 set_device_speed(&ctl);
971
972
973 /*
974 * Unmount all partitions if -m is not specified; or umount given
975 * mountpoint if -M is specified, otherwise print error of another
976 * partition is mounted.
977 */
978 if (!ctl.m_option) {
979 int ct = umount_partitions(&ctl); /* umount all, or count mounted on -M */
980
981 if (ct == 0 && mountpoint)
982 umount_one(&ctl, mountpoint); /* probably whole-device */
983
984 if (ctl.M_option) {
985 if (ct == 1 && mountpoint)
986 umount_one(&ctl, mountpoint);
987 else if (ct)
988 errx(EXIT_FAILURE, _("error: %s: device in use"), ctl.device);
989 }
990 /* Now, we assume the device is no more used, use O_EXCL to be
991 * resistant against our bugs and possible races (someone else
992 * remounted the device).
993 */
994 ctl.force_exclusive = 1;
995 }
996
997 /* handle -c option */
998 if (ctl.c_option) {
999 verbose(&ctl, _("%s: selecting CD-ROM disc #%ld"), ctl.device, ctl.c_arg);
1000 open_device(&ctl);
1001 changer_select(&ctl);
1002 set_device_speed(&ctl);
1003 goto done;
1004 }
1005
1006 /* if user did not specify type of eject, try all four methods */
1007 if (ctl.r_option + ctl.s_option + ctl.f_option + ctl.q_option == 0)
1008 ctl.r_option = ctl.s_option = ctl.f_option = ctl.q_option = 1;
1009
1010 /* open device */
1011 open_device(&ctl);
1012
1013 /* try various methods of ejecting until it works */
1014 if (ctl.r_option) {
1015 verbose(&ctl, _("%s: trying to eject using CD-ROM eject command"), ctl.device);
1016 worked = eject_cdrom(ctl.fd);
1017 verbose(&ctl, worked ? _("CD-ROM eject command succeeded") :
1018 _("CD-ROM eject command failed"));
1019 }
1020
1021 if (ctl.s_option && !worked) {
1022 verbose(&ctl, _("%s: trying to eject using SCSI commands"), ctl.device);
1023 worked = eject_scsi(&ctl);
1024 verbose(&ctl, worked ? _("SCSI eject succeeded") :
1025 _("SCSI eject failed"));
1026 }
1027
1028 if (ctl.f_option && !worked) {
1029 verbose(&ctl, _("%s: trying to eject using floppy eject command"), ctl.device);
1030 worked = eject_floppy(ctl.fd);
1031 verbose(&ctl, worked ? _("floppy eject command succeeded") :
1032 _("floppy eject command failed"));
1033 }
1034
1035 if (ctl.q_option && !worked) {
1036 verbose(&ctl, _("%s: trying to eject using tape offline command"), ctl.device);
1037 worked = eject_tape(ctl.fd);
1038 verbose(&ctl, worked ? _("tape offline command succeeded") :
1039 _("tape offline command failed"));
1040 }
1041
1042 if (!worked)
1043 errx(EXIT_FAILURE, _("unable to eject"));
1044
1045 done:
1046 /* cleanup */
1047 if (ctl.fd >= 0)
1048 close(ctl.fd);
1049
1050 free(ctl.device);
1051 free(mountpoint);
1052
1053 mnt_unref_table(ctl.mtab);
1054
1055 return EXIT_SUCCESS;
1056 }