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