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