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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use std::cmp;
use std::ffi;
use std::fs;
use std::io;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::io::FromRawFd;

mod constants;
mod externs;
mod internal;
mod types;

pub mod error;
pub mod exec;
pub mod fcntl;
pub mod grp;
pub mod lockf;
pub mod net;
pub mod poll;
pub mod pollers;
pub mod power;
pub mod priority;
pub mod process;
pub mod pwd;
pub mod resource;
pub mod select;
pub mod sigaction;
pub mod sigmask;
pub mod signal;
pub mod wait;

#[cfg(any(
    target_os = "linux",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    target_os = "macos",
))]
pub mod flock;

#[macro_export]
macro_rules! attr_group {
    (#![$attr:meta] $($stmts:item)*) => {
        $(
            #[$attr]
            $stmts
        )*
    }
}

attr_group! {
    #![cfg(target_os = "linux")]

    pub mod epoll;
    pub mod inotify;
    pub mod namespace;
    pub mod prctl;
    pub mod signalfd;
}

pub type Short = libc::c_short;
pub type Ushort = libc::c_ushort;
pub type Int = libc::c_int;
pub type Uint = libc::c_uint;
pub type Long = libc::c_long;
pub type Ulong = libc::c_ulong;
pub type LongLong = libc::c_longlong;
pub type UlongLong = libc::c_ulonglong;

pub type SizeT = libc::size_t;
pub type SsizeT = libc::ssize_t;

pub type Char = libc::c_char;
pub type Schar = libc::c_schar;
pub type Uchar = libc::c_uchar;

pub type Float = libc::c_float;
pub type Double = libc::c_double;

pub type IdT = libc::id_t;
pub type PidT = libc::pid_t;
pub type UidT = libc::uid_t;
pub type GidT = libc::gid_t;
pub type OffT = libc::off_t;
pub type SocklenT = libc::socklen_t;

#[cfg(target_os = "linux")]
pub type Off64T = libc::off64_t;

/// Flush filesystem write caches.
///
/// See the man page for sync(2) for more details.
pub fn sync() {
    unsafe { libc::sync() };
}

/// Get the value of runtime constants/limits.
///
/// Given a "name" (one of the `libc::_SC_*` constants),
/// returns the associated configuration value, unless
/// an error occurred (usually when the "name" is not
/// recognized).
///
/// Unlike the `sysconf()` wrapper, this function does not
/// treat return values < 0 specially; that is left to the
/// user.
pub fn sysconf_raw(name: Int) -> io::Result<Long> {
    error::set_errno_success();
    error::convert_if_errno_ret(unsafe { libc::sysconf(name) })
}

/// Get the value of runtime constants/limits.
///
/// Given a "name" (one of the `libc::_SC_*` constants),
/// returns the associated configuration value.
///
/// `None` is returned if an error occurs (usually when
/// the "name" is not recognized) OR if the value returned
/// by the C function `sysconf()` is < 0 (usually indicates
/// no limit). To differentiate between these two
/// possibilities, use `sysconf_raw()`.
pub fn sysconf(name: Int) -> Option<Long> {
    match sysconf_raw(name) {
        Ok(ret) => {
            if ret < 0 {
                return None;
            }
            Some(ret)
        }
        Err(_) => None,
    }
}

/// Constrain a value to a particular range.
///
/// This is included because sometimes when using `sysconf()`
/// it's helpful to constrain a value to a sane range before
/// using it as a buffer size or similar.
pub fn constrain<T: Ord + Eq>(val: T, min: T, max: T) -> T {
    // Help users who get the order wrong
    debug_assert!(max >= min);

    cmp::min(cmp::max(val, min), max)
}

pub fn pipe_raw() -> io::Result<(Int, Int)> {
    let mut fds = [0; 2];

    error::convert_nzero_ret(unsafe { libc::pipe(fds.as_mut_ptr()) })?;

    Ok((fds[0], fds[1]))
}

pub fn pipe() -> io::Result<(fs::File, fs::File)> {
    let (r, w) = pipe_raw()?;
    unsafe { Ok((fs::File::from_raw_fd(r), fs::File::from_raw_fd(w))) }
}

#[cfg(any(
    target_os = "linux",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
))]
pub fn pipe2_raw(flags: Int) -> io::Result<(Int, Int)> {
    let mut fds = [0; 2];

    error::convert_nzero_ret(unsafe { libc::pipe2(fds.as_mut_ptr(), flags) })?;

    Ok((fds[0], fds[1]))
}

#[cfg(any(
    target_os = "linux",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
))]
pub fn pipe2(flags: Int) -> io::Result<(fs::File, fs::File)> {
    let (r, w) = pipe2_raw(flags)?;
    unsafe { Ok((fs::File::from_raw_fd(r), fs::File::from_raw_fd(w))) }
}

/// Closes the given file descriptor.
///
/// # Safety
///
/// If used to close file descriptors opened by builtin types (such as `File`
/// or `TcpStream`), this could violate assumptions made by those types, or
/// code that uses them.
pub unsafe fn close_fd(fd: Int) -> io::Result<()> {
    error::convert_nzero_ret(libc::close(fd))
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum KillSpec {
    /// Kill by process ID (must be > 0)
    Pid(PidT),
    /// Kill by process group ID (must be > 1)
    Pgid(PidT),
    /// All processes in this process's process group
    CurPgrp,
    /// All processes except an implementation-defined list
    ///
    /// On Linux, this kills everything except the current process and PID 1.
    All,
}

pub fn kill(spec: KillSpec, sig: Int) -> io::Result<()> {
    let pid = match spec {
        KillSpec::Pid(pid) => pid,
        KillSpec::Pgid(pgid) => -pgid,
        KillSpec::CurPgrp => 0,
        KillSpec::All => -1,
    };

    error::convert_nzero_ret(unsafe { libc::kill(pid, sig) })
}

pub fn killpg(pgid: PidT, sig: Int) -> io::Result<()> {
    error::convert_nzero_ret(unsafe { libc::killpg(pgid, sig) })
}

#[cfg(target_os = "linux")]
pub fn tgkill(tgid: Int, tid: Int, sig: Int) -> io::Result<()> {
    error::convert_nzero_ret(unsafe { libc::syscall(libc::SYS_tgkill, tgid, tid, sig) })
}

#[cfg(any(target_os = "linux", target_os = "openbsd", target_os = "netbsd"))]
type SetHostnameSize = SizeT;

#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "macos"))]
type SetHostnameSize = Int;

#[cfg(any(
    target_os = "linux",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    target_os = "macos",
))]
pub fn sethostname(name: &ffi::OsString) -> io::Result<()> {
    let name_vec: Vec<Char> = name.clone().into_vec().iter().map(|&x| x as Char).collect();
    error::convert_nzero_ret(unsafe {
        libc::sethostname(name_vec.as_ptr(), name_vec.len() as SetHostnameSize)
    })
}

/// Attempts to read the current system hostname into the given slice.
///
/// The result is null-terminated. Behavior in the case that the vector
/// is not long enough is system-dependent.
pub fn gethostname_raw(name_vec: &mut [Char]) -> io::Result<()> {
    error::convert_nzero_ret(unsafe { libc::gethostname(name_vec.as_mut_ptr(), name_vec.len()) })
}

/// Attempts to determine the current system hostname.
pub fn gethostname() -> io::Result<ffi::OsString> {
    let mut name_vec = Vec::new();
    let orig_size = constrain(sysconf(libc::_SC_HOST_NAME_MAX).unwrap_or(255), 10, 1024) as usize;
    name_vec.resize(orig_size, 0);

    loop {
        match gethostname_raw(&mut name_vec) {
            Ok(()) => {
                let name = bytes_to_osstring(&name_vec);

                if name.len() >= name_vec.len() - 1 {
                    // Either no NULL byte was added, or it was added at the very end
                    // of the vector. The name may have been truncated; increase the size and try
                    // again.

                    if name_vec.len() < orig_size * 10 {
                        name_vec.resize(name_vec.len() * 2, 0);
                        continue;
                    }
                }

                return Ok(name);
            }
            Err(e) => {
                if let Some(raw_err) = e.raw_os_error() {
                    if (raw_err == libc::EINVAL || raw_err == libc::ENAMETOOLONG)
                        && name_vec.len() < orig_size * 10
                    {
                        name_vec.resize(name_vec.len() * 2, 0);
                        continue;
                    }
                }

                return Err(e);
            }
        };
    }
}

#[cfg(target_os = "linux")]
pub fn setdomainname(name: &ffi::OsString) -> io::Result<()> {
    let name_vec: Vec<Char> = name.clone().into_vec().iter().map(|&x| x as Char).collect();
    error::convert_nzero_ret(unsafe { libc::setdomainname(name_vec.as_ptr(), name_vec.len()) })
}

#[cfg(target_os = "linux")]
pub fn getdomainname_raw(name_vec: &mut Vec<Char>) -> io::Result<()> {
    error::convert_nzero_ret(unsafe { libc::getdomainname(name_vec.as_mut_ptr(), name_vec.len()) })
}

#[cfg(target_os = "linux")]
pub fn getdomainname() -> io::Result<ffi::OsString> {
    let mut name_vec = Vec::new();
    let orig_size = 128;
    name_vec.resize(orig_size, 0);

    loop {
        match getdomainname_raw(&mut name_vec) {
            Ok(()) => {
                let name = bytes_to_osstring(&name_vec);

                if name.len() >= name_vec.len() - 1 {
                    // Either no NULL byte was added, or it was added at the very end
                    // of the vector. The name may have been truncated; increase the size and try
                    // again.

                    if name_vec.len() < orig_size * 10 {
                        name_vec.resize(name_vec.len() * 2, 0);
                        continue;
                    }
                }

                return Ok(name);
            }
            Err(e) => {
                if error::is_einval(&e) && name_vec.len() < orig_size * 10 {
                    name_vec.resize(name_vec.len() * 2, 0);
                    continue;
                }

                return Err(e);
            }
        };
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Utsname {
    pub sysname: ffi::OsString,
    pub nodename: ffi::OsString,
    pub release: ffi::OsString,
    pub version: ffi::OsString,
    pub machine: ffi::OsString,
    #[cfg(target_os = "linux")]
    pub domainname: ffi::OsString,
}

/// Returns a `Utsname` struct containing information about the
/// current system.
pub fn uname() -> io::Result<Utsname> {
    let mut utsname = unsafe { std::mem::zeroed::<libc::utsname>() };

    error::convert_nzero_ret(unsafe { libc::uname(&mut utsname) })?;

    Ok(Utsname {
        sysname: bytes_to_osstring(utsname.sysname.iter()),
        nodename: bytes_to_osstring(utsname.nodename.iter()),
        release: bytes_to_osstring(utsname.release.iter()),
        version: bytes_to_osstring(utsname.version.iter()),
        machine: bytes_to_osstring(utsname.machine.iter()),
        #[cfg(target_os = "linux")]
        domainname: bytes_to_osstring(utsname.domainname.iter()),
    })
}

/// This takes a type that implements IntoIterator<Item=&Char> and constructs an OsString.
fn bytes_to_osstring<'a, T: IntoIterator<Item = &'a Char>>(bytes: T) -> ffi::OsString {
    ffi::OsString::from_vec(
        bytes
            .into_iter()
            .take_while(|x| **x != 0)
            .map(|x| *x as u8)
            .collect(),
    )
}

attr_group! {
    #![cfg(target_os = "linux")]

    use std::os::unix::ffi::OsStrExt;

    fn getxattr_raw_internal(
        path: &ffi::CStr,
        name: &ffi::CStr,
        value: &mut [u8],
        follow_links: bool,
    ) -> io::Result<usize> {
        let callback_fn = if follow_links {
            libc::getxattr
        } else {
            libc::lgetxattr
        };

        let n = error::convert_neg_ret(unsafe {
            callback_fn(
                path.as_ptr(),
                name.as_ptr(),
                value.as_mut_ptr() as *mut libc::c_void,
                value.len(),
            )
        })?;

        Ok(n as usize)
    }

    pub fn getxattr_raw<P: AsRef<ffi::OsStr>, N: AsRef<ffi::OsStr>>(
        path: P,
        name: N,
        value: &mut [u8],
        follow_links: bool,
    ) -> io::Result<usize> {
        let c_path = ffi::CString::new(path.as_ref().as_bytes())?;
        let c_name = ffi::CString::new(name.as_ref().as_bytes())?;

        getxattr_raw_internal(&c_path, &c_name, value, follow_links)
    }

    pub fn getxattr<P: AsRef<ffi::OsStr>, N: AsRef<ffi::OsStr>>(
        path: P,
        name: N,
        follow_links: bool,
    ) -> io::Result<Vec<u8>> {
        let c_path = ffi::CString::new(path.as_ref().as_bytes())?;
        let c_name = ffi::CString::new(name.as_ref().as_bytes())?;

        let mut buf = Vec::new();
        let init_size = getxattr_raw_internal(&c_path, &c_name, &mut buf, follow_links)?;
        buf.resize(init_size, 0);

        loop {
            match getxattr_raw_internal(&c_path, &c_name, &mut buf, follow_links) {
                Ok(n) => {
                    buf.resize(n as usize, 0);

                    return Ok(buf);
                }
                Err(e) => {
                    if !error::is_erange(&e) || buf.len() > init_size * 4 {
                        return Err(e);
                    }
                }
            }

            buf.resize(buf.len() * 2, 0);
        }
    }

    fn fgetxattr_raw_internal(fd: Int, name: &ffi::CStr, value: &mut [u8]) -> io::Result<usize> {
        let n = error::convert_neg_ret(unsafe {
            libc::fgetxattr(
                fd,
                name.as_ptr(),
                value.as_mut_ptr() as *mut libc::c_void,
                value.len(),
            )
        })?;

        Ok(n as usize)
    }

    pub fn fgetxattr_raw<N: AsRef<ffi::OsStr>>(
        fd: Int,
        name: N,
        value: &mut [u8],
    ) -> io::Result<usize> {
        let c_name = ffi::CString::new(name.as_ref().as_bytes())?;

        fgetxattr_raw_internal(fd, &c_name, value)
    }

    pub fn fgetxattr<N: AsRef<ffi::OsStr>>(fd: Int, name: N) -> io::Result<Vec<u8>> {
        let c_name = ffi::CString::new(name.as_ref().as_bytes())?;

        let mut buf = Vec::new();
        let init_size = fgetxattr_raw_internal(fd, &c_name, &mut buf)?;
        buf.resize(init_size, 0);

        loop {
            match fgetxattr_raw_internal(fd, &c_name, &mut buf) {
                Ok(n) => {
                    buf.resize(n, 0);

                    return Ok(buf);
                }
                Err(e) => {
                    if !error::is_erange(&e) || buf.len() > init_size * 4 {
                        return Err(e);
                    }
                }
            }

            buf.resize(buf.len() * 2, 0);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Read, Write};

    use super::*;

    #[test]
    fn test_sync() {
        sync();
    }

    #[test]
    fn test_constrain() {
        assert_eq!(constrain(-1, 0, 10), 0);
        assert_eq!(constrain(3, 0, 10), 3);
        assert_eq!(constrain(13, 0, 10), 10);
    }

    #[test]
    fn test_pipe() {
        let (mut r, mut w) = pipe().unwrap();
        let mut buf: Vec<u8> = Vec::new();

        buf.resize(5, 10);
        w.write_all(&[0, 1, 2, 3]).unwrap();
        assert_eq!(r.read(&mut buf).unwrap(), 4);
        assert_eq!(buf, &[0, 1, 2, 3, 10]);

        w.write_all(&[4, 5, 6, 7]).unwrap();
        drop(w);
        buf.clear();
        r.read_to_end(&mut buf).unwrap();
        assert_eq!(buf, &[4, 5, 6, 7]);

        let (r, w) = pipe_raw().unwrap();
        unsafe {
            close_fd(r).unwrap();
            close_fd(w).unwrap();
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_pipe2() {
        let (mut r, mut w) = pipe2(0).unwrap();
        let mut buf: Vec<u8> = Vec::new();

        buf.resize(5, 10);
        w.write_all(&[0, 1, 2, 3]).unwrap();
        assert_eq!(r.read(&mut buf).unwrap(), 4);
        assert_eq!(buf, &[0, 1, 2, 3, 10]);

        w.write_all(&[4, 5, 6, 7]).unwrap();
        drop(w);
        buf.clear();
        r.read_to_end(&mut buf).unwrap();
        assert_eq!(buf, &[4, 5, 6, 7]);

        let (r, w) = pipe2_raw(0).unwrap();
        unsafe {
            close_fd(r).unwrap();
            close_fd(w).unwrap();
        }
    }

    #[test]
    fn test_uname_hostname() {
        uname().unwrap();
        gethostname().unwrap();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_domainname() {
        getdomainname().unwrap();
    }
}