rust/chg/src/procutil.rs
author Yuya Nishihara <yuya@tcha.org>
Mon, 24 Sep 2018 18:33:46 +0900
changeset 39977 44840bcc411a
parent 39974 ba447b83cd56
child 40121 89742f1fa6cb
permissions -rw-r--r--
rust-chg: port basic socket path handling from cHg of C This is basically modeled after setcmdserveropts() of chg.c.

// Copyright 2018 Yuya Nishihara <yuya@tcha.org>
//
// This software may be used and distributed according to the terms of the
// GNU General Public License version 2 or any later version.

//! Low-level utility for signal and process handling.

use libc::{self, c_int, size_t, ssize_t};
use std::io;
use std::os::unix::io::RawFd;

#[link(name = "procutil", kind = "static")]
extern "C" {
    // sendfds.c
    fn sendfds(sockfd: c_int, fds: *const c_int, fdlen: size_t) -> ssize_t;
}

/// Returns the effective uid of the current process.
pub fn get_effective_uid() -> u32 {
    unsafe { libc::geteuid() }
}

/// Changes the given fd to blocking mode.
pub fn set_blocking_fd(fd: RawFd) -> io::Result<()> {
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 {
        return Err(io::Error::last_os_error());
    }
    let r = unsafe { libc::fcntl(fd, libc::F_SETFL, flags & !libc::O_NONBLOCK) };
    if r < 0 {
        return Err(io::Error::last_os_error())
    }
    Ok(())
}

/// Sends file descriptors via the given socket.
pub fn send_raw_fds(sock_fd: RawFd, fds: &[RawFd]) -> io::Result<()> {
    let r = unsafe { sendfds(sock_fd, fds.as_ptr(), fds.len() as size_t) };
    if r < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}