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
// This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

// spell-checker:ignore (ToDO) parsemode makedev sysmacros makenod newmode perror IFBLK IFCHR IFIFO

mod parsemode;

#[macro_use]
extern crate uucore;

use libc::{dev_t, mode_t};
use libc::{S_IFBLK, S_IFCHR, S_IFIFO, S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR};

use getopts::Options;

use std::ffi::CString;

static NAME: &str = "mknod";
static VERSION: &str = env!("CARGO_PKG_VERSION");

const MODE_RW_UGO: mode_t = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;

#[inline(always)]
fn makedev(maj: u64, min: u64) -> dev_t {
    // pick up from <sys/sysmacros.h>
    ((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32)) as dev_t
}

#[cfg(windows)]
fn _makenod(path: CString, mode: mode_t, dev: dev_t) -> i32 {
    panic!("Unsupported for windows platform")
}

#[cfg(unix)]
fn _makenod(path: CString, mode: mode_t, dev: dev_t) -> i32 {
    unsafe { libc::mknod(path.as_ptr(), mode, dev) }
}

#[allow(clippy::cognitive_complexity)]
pub fn uumain(args: impl uucore::Args) -> i32 {
    let args = args.collect_str();

    let mut opts = Options::new();

    // Linux-specific options, not implemented
    // opts.optflag("Z", "", "set the SELinux security context to default type");
    // opts.optopt("", "context", "like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX");
    opts.optopt(
        "m",
        "mode",
        "set file permission bits to MODE, not a=rw - umask",
        "MODE",
    );

    opts.optflag("", "help", "display this help and exit");
    opts.optflag("", "version", "output version information and exit");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => crash!(1, "{}\nTry '{} --help' for more information.", f, NAME),
    };

    if matches.opt_present("help") {
        println!(
            "Usage: {0} [OPTION]... NAME TYPE [MAJOR MINOR]

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE    set file permission bits to MODE, not a=rw - umask
      --help     display this help and exit
      --version  output version information and exit

Both MAJOR and MINOR must be specified when TYPE is b, c, or u, and they
must be omitted when TYPE is p.  If MAJOR or MINOR begins with 0x or 0X,
it is interpreted as hexadecimal; otherwise, if it begins with 0, as octal;
otherwise, as decimal.  TYPE may be:

  b      create a block (buffered) special file
  c, u   create a character (unbuffered) special file
  p      create a FIFO

NOTE: your shell may have its own version of mknod, which usually supersedes
the version described here.  Please refer to your shell's documentation
for details about the options it supports.",
            NAME
        );
        return 0;
    }

    if matches.opt_present("version") {
        println!("{} {}", NAME, VERSION);
        return 0;
    }

    let mut last_umask: mode_t = 0;
    let mut newmode: mode_t = MODE_RW_UGO;
    if matches.opt_present("mode") {
        match parsemode::parse_mode(matches.opt_str("mode")) {
            Ok(parsed) => {
                if parsed > 0o777 {
                    show_info!("mode must specify only file permission bits");
                    return 1;
                }
                newmode = parsed;
            }
            Err(e) => {
                show_info!("{}", e);
                return 1;
            }
        }
        unsafe {
            last_umask = libc::umask(0);
        }
    }

    let mut ret = 0i32;
    match matches.free.len() {
        0 => show_usage_error!("missing operand"),
        1 => show_usage_error!("missing operand after ‘{}’", matches.free[0]),
        _ => {
            let args = &matches.free;
            let c_str = CString::new(args[0].as_str()).expect("Failed to convert to CString");

            // Only check the first character, to allow mnemonic usage like
            // 'mknod /dev/rst0 character 18 0'.
            let ch = args[1]
                .chars()
                .next()
                .expect("Failed to get the first char");

            if ch == 'p' {
                if args.len() > 2 {
                    show_info!("{}: extra operand ‘{}’", NAME, args[2]);
                    if args.len() == 4 {
                        eprintln!("Fifos do not have major and minor device numbers.");
                    }
                    eprintln!("Try '{} --help' for more information.", NAME);
                    return 1;
                }

                ret = _makenod(c_str, S_IFIFO | newmode, 0);
            } else {
                if args.len() < 4 {
                    show_info!("missing operand after ‘{}’", args[args.len() - 1]);
                    if args.len() == 2 {
                        eprintln!("Special files require major and minor device numbers.");
                    }
                    eprintln!("Try '{} --help' for more information.", NAME);
                    return 1;
                } else if args.len() > 4 {
                    show_usage_error!("extra operand ‘{}’", args[4]);
                    return 1;
                } else if !"bcu".contains(ch) {
                    show_usage_error!("invalid device type ‘{}’", args[1]);
                    return 1;
                }

                let maj = args[2].parse::<u64>();
                let min = args[3].parse::<u64>();
                if maj.is_err() {
                    show_info!("invalid major device number ‘{}’", args[2]);
                    return 1;
                } else if min.is_err() {
                    show_info!("invalid minor device number ‘{}’", args[3]);
                    return 1;
                }

                let (maj, min) = (maj.unwrap(), min.unwrap());
                let dev = makedev(maj, min);
                if ch == 'b' {
                    // block special file
                    ret = _makenod(c_str, S_IFBLK | newmode, dev);
                } else {
                    // char special file
                    ret = _makenod(c_str, S_IFCHR | newmode, dev);
                }
            }
        }
    }

    if last_umask != 0 {
        unsafe {
            libc::umask(last_umask);
        }
    }
    if ret == -1 {
        let c_str = CString::new(format!("{}: {}", NAME, matches.free[0]).as_str())
            .expect("Failed to convert to CString");
        unsafe {
            libc::perror(c_str.as_ptr());
        }
    }

    ret
}