linuxutils-system 0.1.0

System utilities from linuxutils
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use linuxutils_common::man::ManContent;

pub const MAN: ManContent = ManContent::empty();

use clap::Parser;
use std::{
    fs::{self, File},
    io::{self, BufRead},
    process::{Command, ExitCode},
};

const DEFAULT_DEVICE: &str = "/dev/cdrom";

// CD-ROM ioctls
const CDROMEJECT: libc::c_ulong = 0x5309;
const CDROMCLOSETRAY: libc::c_ulong = 0x5319;
const CDROM_LOCKDOOR: libc::c_ulong = 0x5329;
const CDROM_DRIVE_STATUS: libc::c_ulong = 0x5326;

// Drive status results
const CDS_TRAY_OPEN: i32 = 2;

// Floppy ioctl
const FDEJECT: libc::c_ulong = 0x025a;

// Tape ioctl
const MTIOCTOP: libc::c_ulong = 0x4d01;
const MTOFFL: i16 = 7;

// SCSI
const SG_IO: libc::c_ulong = 0x2285;
const SG_DXFER_NONE: i32 = -1;

#[repr(C)]
struct MtOp {
    mt_op: i16,
    mt_count: i32,
}

#[repr(C)]
struct SgIoHdr {
    interface_id: i32,
    dxfer_direction: i32,
    cmd_len: u8,
    mx_sb_len: u8,
    iovec_count: u16,
    dxfer_len: u32,
    dxferp: *mut libc::c_void,
    cmdp: *const u8,
    sbp: *mut u8,
    timeout: u32,
    flags: u32,
    pack_id: i32,
    usr_ptr: *mut libc::c_void,
    status: u8,
    masked_status: u8,
    msg_status: u8,
    sb_len_wr: u8,
    host_status: u16,
    driver_status: u16,
    resid: i32,
    duration: u32,
    info: u32,
}

#[derive(Parser)]
#[command(name = "eject", about = "Eject removable media")]
pub struct Args {
    /// Display default device name
    #[arg(short = 'd', long = "default")]
    default: bool,

    /// Force eject, skip device type check
    #[arg(short = 'F', long)]
    force: bool,

    /// Use floppy eject method
    #[arg(short = 'f', long)]
    floppy: bool,

    /// Lock or unlock hardware eject button (on|off)
    #[arg(short = 'i', long = "manualeject")]
    manualeject: Option<String>,

    /// Don't unmount other partitions on the device
    #[arg(short = 'M', long = "no-partitions-unmount")]
    no_partitions_unmount: bool,

    /// Don't unmount the device before ejecting
    #[arg(short = 'm', long = "no-unmount")]
    no_unmount: bool,

    /// Show device but take no action
    #[arg(short = 'n', long)]
    noop: bool,

    /// Use tape drive offline command
    #[arg(short = 'q', long)]
    tape: bool,

    /// Use CD-ROM eject command
    #[arg(short = 'r', long)]
    cdrom: bool,

    /// Use SCSI eject commands
    #[arg(short = 's', long)]
    scsi: bool,

    /// Toggle tray open/close
    #[arg(short = 'T', long)]
    traytoggle: bool,

    /// Close CD-ROM tray
    #[arg(short = 't', long)]
    trayclose: bool,

    /// Verbose output
    #[arg(short = 'v', long)]
    verbose: bool,

    /// Device or mountpoint to eject
    device: Option<String>,
}

fn resolve_device(device: &str) -> String {
    // If it's a mountpoint, find the device from /proc/mounts
    if let Ok(file) = File::open("/proc/mounts") {
        for line in io::BufReader::new(file).lines().map_while(Result::ok) {
            let fields: Vec<&str> = line.split_whitespace().collect();
            if fields.len() >= 2 && fields[1] == device {
                return fields[0].to_string();
            }
        }
    }
    // Follow symlinks
    fs::canonicalize(device)
        .ok()
        .and_then(|p| p.to_str().map(|s| s.to_string()))
        .unwrap_or_else(|| device.to_string())
}

fn find_mounts(device: &str) -> Vec<String> {
    let mut mounts = Vec::new();
    let Ok(file) = File::open("/proc/mounts") else {
        return mounts;
    };
    for line in io::BufReader::new(file).lines().map_while(Result::ok) {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() >= 2 && fields[0] == device {
            mounts.push(fields[1].to_string());
        }
    }
    mounts
}

fn unmount(mountpoint: &str, verbose: bool) -> io::Result<()> {
    if verbose {
        eprintln!("eject: unmounting {mountpoint}");
    }
    let status = Command::new("umount").arg(mountpoint).status()?;
    if status.success() {
        Ok(())
    } else {
        Err(io::Error::other(format!("umount {mountpoint} failed")))
    }
}

fn eject_cdrom(fd: i32) -> io::Result<()> {
    if unsafe { libc::ioctl(fd, CDROMEJECT) } < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

fn eject_scsi(fd: i32) -> io::Result<()> {
    // First unlock
    let unlock_cmd: [u8; 6] = [0x1e, 0, 0, 0, 0, 0];
    let mut sense: [u8; 32] = [0; 32];

    let mut hdr: SgIoHdr = unsafe { std::mem::zeroed() };
    hdr.interface_id = b'S' as i32;
    hdr.dxfer_direction = SG_DXFER_NONE;
    hdr.cmd_len = 6;
    hdr.mx_sb_len = sense.len() as u8;
    hdr.cmdp = unlock_cmd.as_ptr();
    hdr.sbp = sense.as_mut_ptr();
    hdr.timeout = 10000;

    if unsafe { libc::ioctl(fd, SG_IO, &mut hdr) } < 0 {
        return Err(io::Error::last_os_error());
    }

    // Then eject: START_STOP with LoEj=1, Start=0
    let eject_cmd: [u8; 6] = [0x1b, 0, 0, 0, 0x02, 0];
    let mut sense2: [u8; 32] = [0; 32];

    let mut hdr2: SgIoHdr = unsafe { std::mem::zeroed() };
    hdr2.interface_id = b'S' as i32;
    hdr2.dxfer_direction = SG_DXFER_NONE;
    hdr2.cmd_len = 6;
    hdr2.mx_sb_len = sense2.len() as u8;
    hdr2.cmdp = eject_cmd.as_ptr();
    hdr2.sbp = sense2.as_mut_ptr();
    hdr2.timeout = 10000;

    if unsafe { libc::ioctl(fd, SG_IO, &mut hdr2) } < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

fn eject_floppy(fd: i32) -> io::Result<()> {
    if unsafe { libc::ioctl(fd, FDEJECT) } < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

fn eject_tape(fd: i32) -> io::Result<()> {
    let op = MtOp {
        mt_op: MTOFFL,
        mt_count: 0,
    };
    if unsafe { libc::ioctl(fd, MTIOCTOP, &op) } < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

fn close_tray(fd: i32) -> io::Result<()> {
    if unsafe { libc::ioctl(fd, CDROMCLOSETRAY) } < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

fn toggle_tray(fd: i32) -> io::Result<()> {
    let status = unsafe { libc::ioctl(fd, CDROM_DRIVE_STATUS, 0) };
    if status < 0 {
        return Err(io::Error::last_os_error());
    }
    if status == CDS_TRAY_OPEN {
        close_tray(fd)
    } else {
        eject_cdrom(fd)
    }
}

fn lock_door(fd: i32, lock: bool) -> io::Result<()> {
    let arg: i32 = if lock { 1 } else { 0 };
    if unsafe { libc::ioctl(fd, CDROM_LOCKDOOR, arg) } < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

pub fn run(args: Args) -> ExitCode {
    if args.default {
        println!("{DEFAULT_DEVICE}");
        return ExitCode::SUCCESS;
    }

    let device = args.device.as_deref().unwrap_or(DEFAULT_DEVICE);
    let device = resolve_device(device);

    if args.noop {
        println!("{device}");
        return ExitCode::SUCCESS;
    }

    if args.verbose {
        eprintln!("eject: device is '{device}'");
    }

    // Unmount if needed
    if !args.no_unmount
        && args.manualeject.is_none()
        && !args.trayclose
        && !args.traytoggle
    {
        let mounts = find_mounts(&device);
        for mp in &mounts {
            if let Err(e) = unmount(mp, args.verbose) {
                eprintln!("eject: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // Open device
    let flags = if args.force {
        libc::O_RDONLY | libc::O_NONBLOCK
    } else {
        libc::O_RDONLY | libc::O_NONBLOCK | libc::O_EXCL
    };
    let dev_cstr = match std::ffi::CString::new(device.as_str()) {
        Ok(c) => c,
        Err(_) => {
            eprintln!("eject: invalid device path");
            return ExitCode::FAILURE;
        }
    };
    let fd = unsafe { libc::open(dev_cstr.as_ptr(), flags) };
    if fd < 0 {
        eprintln!(
            "eject: failed to open '{device}': {}",
            io::Error::last_os_error()
        );
        return ExitCode::FAILURE;
    }

    let result = if let Some(ref val) = args.manualeject {
        match val.as_str() {
            "on" | "1" => {
                if args.verbose {
                    eprintln!("eject: locking door");
                }
                lock_door(fd, true)
            }
            "off" | "0" => {
                if args.verbose {
                    eprintln!("eject: unlocking door");
                }
                lock_door(fd, false)
            }
            other => {
                eprintln!(
                    "eject: invalid --manualeject value '{other}' (expected on|off)"
                );
                unsafe { libc::close(fd) };
                return ExitCode::FAILURE;
            }
        }
    } else if args.trayclose {
        if args.verbose {
            eprintln!("eject: closing tray");
        }
        close_tray(fd)
    } else if args.traytoggle {
        if args.verbose {
            eprintln!("eject: toggling tray");
        }
        toggle_tray(fd)
    } else {
        // Eject: try methods in order, or use specific method
        let specific = args.cdrom || args.scsi || args.floppy || args.tape;

        let mut ok = false;

        if !ok && (args.cdrom || !specific) {
            if args.verbose {
                eprintln!("eject: trying CD-ROM eject");
            }
            if eject_cdrom(fd).is_ok() {
                ok = true;
            }
        }
        if !ok && (args.scsi || !specific) {
            if args.verbose {
                eprintln!("eject: trying SCSI eject");
            }
            if eject_scsi(fd).is_ok() {
                ok = true;
            }
        }
        if !ok && (args.floppy || !specific) {
            if args.verbose {
                eprintln!("eject: trying floppy eject");
            }
            if eject_floppy(fd).is_ok() {
                ok = true;
            }
        }
        if !ok && (args.tape || !specific) {
            if args.verbose {
                eprintln!("eject: trying tape eject");
            }
            if eject_tape(fd).is_ok() {
                ok = true;
            }
        }

        if ok {
            Ok(())
        } else {
            Err(io::Error::other("all eject methods failed"))
        }
    };

    unsafe { libc::close(fd) };

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("eject: {device}: {e}");
            ExitCode::FAILURE
        }
    }
}