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