1 //! Safe wrappers around functions found in libc "unistd.h" header
2 
3 #[cfg(not(target_os = "redox"))]
4 use cfg_if::cfg_if;
5 use crate::errno::{self, Errno};
6 use crate::{Error, Result, NixPath};
7 #[cfg(not(target_os = "redox"))]
8 use crate::fcntl::{AtFlags, at_rawfd};
9 use crate::fcntl::{FdFlag, OFlag, fcntl};
10 use crate::fcntl::FcntlArg::F_SETFD;
11 use libc::{self, c_char, c_void, c_int, c_long, c_uint, size_t, pid_t, off_t,
12            uid_t, gid_t, mode_t, PATH_MAX};
13 use std::{fmt, mem, ptr};
14 use std::convert::Infallible;
15 use std::ffi::{CStr, OsString};
16 #[cfg(not(target_os = "redox"))]
17 use std::ffi::{CString, OsStr};
18 use std::os::unix::ffi::OsStringExt;
19 #[cfg(not(target_os = "redox"))]
20 use std::os::unix::ffi::OsStrExt;
21 use std::os::unix::io::RawFd;
22 use std::path::PathBuf;
23 use crate::sys::stat::Mode;
24 
25 #[cfg(any(target_os = "android", target_os = "linux"))]
26 pub use self::pivot_root::*;
27 
28 #[cfg(any(target_os = "android", target_os = "freebsd",
29           target_os = "linux", target_os = "openbsd"))]
30 pub use self::setres::*;
31 
32 #[cfg(any(target_os = "android", target_os = "linux"))]
33 pub use self::getres::*;
34 
35 /// User identifier
36 ///
37 /// Newtype pattern around `uid_t` (which is just alias). It prevents bugs caused by accidentally
38 /// passing wrong value.
39 #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
40 pub struct Uid(uid_t);
41 
42 impl Uid {
43     /// Creates `Uid` from raw `uid_t`.
from_raw(uid: uid_t) -> Self44     pub const fn from_raw(uid: uid_t) -> Self {
45         Uid(uid)
46     }
47 
48     /// Returns Uid of calling process. This is practically a more Rusty alias for `getuid`.
current() -> Self49     pub fn current() -> Self {
50         getuid()
51     }
52 
53     /// Returns effective Uid of calling process. This is practically a more Rusty alias for `geteuid`.
effective() -> Self54     pub fn effective() -> Self {
55         geteuid()
56     }
57 
58     /// Returns true if the `Uid` represents privileged user - root. (If it equals zero.)
is_root(self) -> bool59     pub const fn is_root(self) -> bool {
60         self.0 == ROOT.0
61     }
62 
63     /// Get the raw `uid_t` wrapped by `self`.
as_raw(self) -> uid_t64     pub const fn as_raw(self) -> uid_t {
65         self.0
66     }
67 }
68 
69 impl From<Uid> for uid_t {
from(uid: Uid) -> Self70     fn from(uid: Uid) -> Self {
71         uid.0
72     }
73 }
74 
75 impl fmt::Display for Uid {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result76     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77         fmt::Display::fmt(&self.0, f)
78     }
79 }
80 
81 /// Constant for UID = 0
82 pub const ROOT: Uid = Uid(0);
83 
84 /// Group identifier
85 ///
86 /// Newtype pattern around `gid_t` (which is just alias). It prevents bugs caused by accidentally
87 /// passing wrong value.
88 #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
89 pub struct Gid(gid_t);
90 
91 impl Gid {
92     /// Creates `Gid` from raw `gid_t`.
from_raw(gid: gid_t) -> Self93     pub const fn from_raw(gid: gid_t) -> Self {
94         Gid(gid)
95     }
96 
97     /// Returns Gid of calling process. This is practically a more Rusty alias for `getgid`.
current() -> Self98     pub fn current() -> Self {
99         getgid()
100     }
101 
102     /// Returns effective Gid of calling process. This is practically a more Rusty alias for `getegid`.
effective() -> Self103     pub fn effective() -> Self {
104         getegid()
105     }
106 
107     /// Get the raw `gid_t` wrapped by `self`.
as_raw(self) -> gid_t108     pub const fn as_raw(self) -> gid_t {
109         self.0
110     }
111 }
112 
113 impl From<Gid> for gid_t {
from(gid: Gid) -> Self114     fn from(gid: Gid) -> Self {
115         gid.0
116     }
117 }
118 
119 impl fmt::Display for Gid {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result120     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121         fmt::Display::fmt(&self.0, f)
122     }
123 }
124 
125 /// Process identifier
126 ///
127 /// Newtype pattern around `pid_t` (which is just alias). It prevents bugs caused by accidentally
128 /// passing wrong value.
129 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
130 pub struct Pid(pid_t);
131 
132 impl Pid {
133     /// Creates `Pid` from raw `pid_t`.
from_raw(pid: pid_t) -> Self134     pub const fn from_raw(pid: pid_t) -> Self {
135         Pid(pid)
136     }
137 
138     /// Returns PID of calling process
this() -> Self139     pub fn this() -> Self {
140         getpid()
141     }
142 
143     /// Returns PID of parent of calling process
parent() -> Self144     pub fn parent() -> Self {
145         getppid()
146     }
147 
148     /// Get the raw `pid_t` wrapped by `self`.
as_raw(self) -> pid_t149     pub const fn as_raw(self) -> pid_t {
150         self.0
151     }
152 }
153 
154 impl From<Pid> for pid_t {
from(pid: Pid) -> Self155     fn from(pid: Pid) -> Self {
156         pid.0
157     }
158 }
159 
160 impl fmt::Display for Pid {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result161     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162         fmt::Display::fmt(&self.0, f)
163     }
164 }
165 
166 
167 /// Represents the successful result of calling `fork`
168 ///
169 /// When `fork` is called, the process continues execution in the parent process
170 /// and in the new child.  This return type can be examined to determine whether
171 /// you are now executing in the parent process or in the child.
172 #[derive(Clone, Copy, Debug)]
173 pub enum ForkResult {
174     Parent { child: Pid },
175     Child,
176 }
177 
178 impl ForkResult {
179 
180     /// Return `true` if this is the child process of the `fork()`
181     #[inline]
is_child(self) -> bool182     pub fn is_child(self) -> bool {
183         match self {
184             ForkResult::Child => true,
185             _ => false
186         }
187     }
188 
189     /// Returns `true` if this is the parent process of the `fork()`
190     #[inline]
is_parent(self) -> bool191     pub fn is_parent(self) -> bool {
192         !self.is_child()
193     }
194 }
195 
196 /// Create a new child process duplicating the parent process ([see
197 /// fork(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html)).
198 ///
199 /// After calling the fork system call (successfully) two processes will
200 /// be created that are identical with the exception of their pid and the
201 /// return value of this function.  As an example:
202 ///
203 /// ```no_run
204 /// use nix::unistd::{fork, ForkResult};
205 ///
206 /// match unsafe{fork()} {
207 ///    Ok(ForkResult::Parent { child, .. }) => {
208 ///        println!("Continuing execution in parent process, new child has pid: {}", child);
209 ///    }
210 ///    Ok(ForkResult::Child) => println!("I'm a new child process"),
211 ///    Err(_) => println!("Fork failed"),
212 /// }
213 /// ```
214 ///
215 /// This will print something like the following (order indeterministic).  The
216 /// thing to note is that you end up with two processes continuing execution
217 /// immediately after the fork call but with different match arms.
218 ///
219 /// ```text
220 /// Continuing execution in parent process, new child has pid: 1234
221 /// I'm a new child process
222 /// ```
223 ///
224 /// # Safety
225 ///
226 /// In a multithreaded program, only [async-signal-safe] functions like `pause`
227 /// and `_exit` may be called by the child (the parent isn't restricted). Note
228 /// that memory allocation may **not** be async-signal-safe and thus must be
229 /// prevented.
230 ///
231 /// Those functions are only a small subset of your operating system's API, so
232 /// special care must be taken to only invoke code you can control and audit.
233 ///
234 /// [async-signal-safe]: https://man7.org/linux/man-pages/man7/signal-safety.7.html
235 #[inline]
fork() -> Result<ForkResult>236 pub unsafe fn fork() -> Result<ForkResult> {
237     use self::ForkResult::*;
238     let res = libc::fork();
239 
240     Errno::result(res).map(|res| match res {
241         0 => Child,
242         res => Parent { child: Pid(res) },
243     })
244 }
245 
246 /// Get the pid of this process (see
247 /// [getpid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpid.html)).
248 ///
249 /// Since you are running code, there is always a pid to return, so there
250 /// is no error case that needs to be handled.
251 #[inline]
getpid() -> Pid252 pub fn getpid() -> Pid {
253     Pid(unsafe { libc::getpid() })
254 }
255 
256 /// Get the pid of this processes' parent (see
257 /// [getpid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getppid.html)).
258 ///
259 /// There is always a parent pid to return, so there is no error case that needs
260 /// to be handled.
261 #[inline]
getppid() -> Pid262 pub fn getppid() -> Pid {
263     Pid(unsafe { libc::getppid() }) // no error handling, according to man page: "These functions are always successful."
264 }
265 
266 /// Set a process group ID (see
267 /// [setpgid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setpgid.html)).
268 ///
269 /// Set the process group id (PGID) of a particular process.  If a pid of zero
270 /// is specified, then the pid of the calling process is used.  Process groups
271 /// may be used to group together a set of processes in order for the OS to
272 /// apply some operations across the group.
273 ///
274 /// `setsid()` may be used to create a new process group.
275 #[inline]
setpgid(pid: Pid, pgid: Pid) -> Result<()>276 pub fn setpgid(pid: Pid, pgid: Pid) -> Result<()> {
277     let res = unsafe { libc::setpgid(pid.into(), pgid.into()) };
278     Errno::result(res).map(drop)
279 }
280 #[inline]
getpgid(pid: Option<Pid>) -> Result<Pid>281 pub fn getpgid(pid: Option<Pid>) -> Result<Pid> {
282     let res = unsafe { libc::getpgid(pid.unwrap_or(Pid(0)).into()) };
283     Errno::result(res).map(Pid)
284 }
285 
286 /// Create new session and set process group id (see
287 /// [setsid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setsid.html)).
288 #[inline]
setsid() -> Result<Pid>289 pub fn setsid() -> Result<Pid> {
290     Errno::result(unsafe { libc::setsid() }).map(Pid)
291 }
292 
293 /// Get the process group ID of a session leader
294 /// [getsid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsid.html).
295 ///
296 /// Obtain the process group ID of the process that is the session leader of the process specified
297 /// by pid. If pid is zero, it specifies the calling process.
298 #[inline]
299 #[cfg(not(target_os = "redox"))]
getsid(pid: Option<Pid>) -> Result<Pid>300 pub fn getsid(pid: Option<Pid>) -> Result<Pid> {
301     let res = unsafe { libc::getsid(pid.unwrap_or(Pid(0)).into()) };
302     Errno::result(res).map(Pid)
303 }
304 
305 
306 /// Get the terminal foreground process group (see
307 /// [tcgetpgrp(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcgetpgrp.html)).
308 ///
309 /// Get the group process id (GPID) of the foreground process group on the
310 /// terminal associated to file descriptor (FD).
311 #[inline]
tcgetpgrp(fd: c_int) -> Result<Pid>312 pub fn tcgetpgrp(fd: c_int) -> Result<Pid> {
313     let res = unsafe { libc::tcgetpgrp(fd) };
314     Errno::result(res).map(Pid)
315 }
316 /// Set the terminal foreground process group (see
317 /// [tcgetpgrp(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcsetpgrp.html)).
318 ///
319 /// Get the group process id (PGID) to the foreground process group on the
320 /// terminal associated to file descriptor (FD).
321 #[inline]
tcsetpgrp(fd: c_int, pgrp: Pid) -> Result<()>322 pub fn tcsetpgrp(fd: c_int, pgrp: Pid) -> Result<()> {
323     let res = unsafe { libc::tcsetpgrp(fd, pgrp.into()) };
324     Errno::result(res).map(drop)
325 }
326 
327 
328 /// Get the group id of the calling process (see
329 ///[getpgrp(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgrp.html)).
330 ///
331 /// Get the process group id (PGID) of the calling process.
332 /// According to the man page it is always successful.
333 #[inline]
getpgrp() -> Pid334 pub fn getpgrp() -> Pid {
335     Pid(unsafe { libc::getpgrp() })
336 }
337 
338 /// Get the caller's thread ID (see
339 /// [gettid(2)](https://man7.org/linux/man-pages/man2/gettid.2.html).
340 ///
341 /// This function is only available on Linux based systems.  In a single
342 /// threaded process, the main thread will have the same ID as the process.  In
343 /// a multithreaded process, each thread will have a unique thread id but the
344 /// same process ID.
345 ///
346 /// No error handling is required as a thread id should always exist for any
347 /// process, even if threads are not being used.
348 #[cfg(any(target_os = "linux", target_os = "android"))]
349 #[inline]
gettid() -> Pid350 pub fn gettid() -> Pid {
351     Pid(unsafe { libc::syscall(libc::SYS_gettid) as pid_t })
352 }
353 
354 /// Create a copy of the specified file descriptor (see
355 /// [dup(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup.html)).
356 ///
357 /// The new file descriptor will be have a new index but refer to the same
358 /// resource as the old file descriptor and the old and new file descriptors may
359 /// be used interchangeably.  The new and old file descriptor share the same
360 /// underlying resource, offset, and file status flags.  The actual index used
361 /// for the file descriptor will be the lowest fd index that is available.
362 ///
363 /// The two file descriptors do not share file descriptor flags (e.g. `OFlag::FD_CLOEXEC`).
364 #[inline]
dup(oldfd: RawFd) -> Result<RawFd>365 pub fn dup(oldfd: RawFd) -> Result<RawFd> {
366     let res = unsafe { libc::dup(oldfd) };
367 
368     Errno::result(res)
369 }
370 
371 /// Create a copy of the specified file descriptor using the specified fd (see
372 /// [dup(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup.html)).
373 ///
374 /// This function behaves similar to `dup()` except that it will try to use the
375 /// specified fd instead of allocating a new one.  See the man pages for more
376 /// detail on the exact behavior of this function.
377 #[inline]
dup2(oldfd: RawFd, newfd: RawFd) -> Result<RawFd>378 pub fn dup2(oldfd: RawFd, newfd: RawFd) -> Result<RawFd> {
379     let res = unsafe { libc::dup2(oldfd, newfd) };
380 
381     Errno::result(res)
382 }
383 
384 /// Create a new copy of the specified file descriptor using the specified fd
385 /// and flags (see [dup(2)](https://man7.org/linux/man-pages/man2/dup.2.html)).
386 ///
387 /// This function behaves similar to `dup2()` but allows for flags to be
388 /// specified.
dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd>389 pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
390     dup3_polyfill(oldfd, newfd, flags)
391 }
392 
393 #[inline]
dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd>394 fn dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
395     if oldfd == newfd {
396         return Err(Error::from(Errno::EINVAL));
397     }
398 
399     let fd = dup2(oldfd, newfd)?;
400 
401     if flags.contains(OFlag::O_CLOEXEC) {
402         if let Err(e) = fcntl(fd, F_SETFD(FdFlag::FD_CLOEXEC)) {
403             let _ = close(fd);
404             return Err(e);
405         }
406     }
407 
408     Ok(fd)
409 }
410 
411 /// Change the current working directory of the calling process (see
412 /// [chdir(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/chdir.html)).
413 ///
414 /// This function may fail in a number of different scenarios.  See the man
415 /// pages for additional details on possible failure cases.
416 #[inline]
chdir<P: ?Sized + NixPath>(path: &P) -> Result<()>417 pub fn chdir<P: ?Sized + NixPath>(path: &P) -> Result<()> {
418     let res = path.with_nix_path(|cstr| {
419         unsafe { libc::chdir(cstr.as_ptr()) }
420     })?;
421 
422     Errno::result(res).map(drop)
423 }
424 
425 /// Change the current working directory of the process to the one
426 /// given as an open file descriptor (see
427 /// [fchdir(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchdir.html)).
428 ///
429 /// This function may fail in a number of different scenarios.  See the man
430 /// pages for additional details on possible failure cases.
431 #[inline]
432 #[cfg(not(target_os = "fuchsia"))]
fchdir(dirfd: RawFd) -> Result<()>433 pub fn fchdir(dirfd: RawFd) -> Result<()> {
434     let res = unsafe { libc::fchdir(dirfd) };
435 
436     Errno::result(res).map(drop)
437 }
438 
439 /// Creates new directory `path` with access rights `mode`.  (see [mkdir(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdir.html))
440 ///
441 /// # Errors
442 ///
443 /// There are several situations where mkdir might fail:
444 ///
445 /// - current user has insufficient rights in the parent directory
446 /// - the path already exists
447 /// - the path name is too long (longer than `PATH_MAX`, usually 4096 on linux, 1024 on OS X)
448 ///
449 /// # Example
450 ///
451 /// ```rust
452 /// use nix::unistd;
453 /// use nix::sys::stat;
454 /// use tempfile::tempdir;
455 ///
456 /// let tmp_dir1 = tempdir().unwrap();
457 /// let tmp_dir2 = tmp_dir1.path().join("new_dir");
458 ///
459 /// // create new directory and give read, write and execute rights to the owner
460 /// match unistd::mkdir(&tmp_dir2, stat::Mode::S_IRWXU) {
461 ///    Ok(_) => println!("created {:?}", tmp_dir2),
462 ///    Err(err) => println!("Error creating directory: {}", err),
463 /// }
464 /// ```
465 #[inline]
mkdir<P: ?Sized + NixPath>(path: &P, mode: Mode) -> Result<()>466 pub fn mkdir<P: ?Sized + NixPath>(path: &P, mode: Mode) -> Result<()> {
467     let res = path.with_nix_path(|cstr| {
468         unsafe { libc::mkdir(cstr.as_ptr(), mode.bits() as mode_t) }
469     })?;
470 
471     Errno::result(res).map(drop)
472 }
473 
474 /// Creates new fifo special file (named pipe) with path `path` and access rights `mode`.
475 ///
476 /// # Errors
477 ///
478 /// There are several situations where mkfifo might fail:
479 ///
480 /// - current user has insufficient rights in the parent directory
481 /// - the path already exists
482 /// - the path name is too long (longer than `PATH_MAX`, usually 4096 on linux, 1024 on OS X)
483 ///
484 /// For a full list consult
485 /// [posix specification](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkfifo.html)
486 ///
487 /// # Example
488 ///
489 /// ```rust
490 /// use nix::unistd;
491 /// use nix::sys::stat;
492 /// use tempfile::tempdir;
493 ///
494 /// let tmp_dir = tempdir().unwrap();
495 /// let fifo_path = tmp_dir.path().join("foo.pipe");
496 ///
497 /// // create new fifo and give read, write and execute rights to the owner
498 /// match unistd::mkfifo(&fifo_path, stat::Mode::S_IRWXU) {
499 ///    Ok(_) => println!("created {:?}", fifo_path),
500 ///    Err(err) => println!("Error creating fifo: {}", err),
501 /// }
502 /// ```
503 #[inline]
504 #[cfg(not(target_os = "redox"))] // RedoxFS does not support fifo yet
mkfifo<P: ?Sized + NixPath>(path: &P, mode: Mode) -> Result<()>505 pub fn mkfifo<P: ?Sized + NixPath>(path: &P, mode: Mode) -> Result<()> {
506     let res = path.with_nix_path(|cstr| {
507         unsafe { libc::mkfifo(cstr.as_ptr(), mode.bits() as mode_t) }
508     })?;
509 
510     Errno::result(res).map(drop)
511 }
512 
513 /// Creates new fifo special file (named pipe) with path `path` and access rights `mode`.
514 ///
515 /// If `dirfd` has a value, then `path` is relative to directory associated with the file descriptor.
516 ///
517 /// If `dirfd` is `None`, then `path` is relative to the current working directory.
518 ///
519 /// # References
520 ///
521 /// [mkfifoat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkfifoat.html).
522 // mkfifoat is not implemented in OSX or android
523 #[inline]
524 #[cfg(not(any(
525     target_os = "macos", target_os = "ios",
526     target_os = "android", target_os = "redox")))]
mkfifoat<P: ?Sized + NixPath>(dirfd: Option<RawFd>, path: &P, mode: Mode) -> Result<()>527 pub fn mkfifoat<P: ?Sized + NixPath>(dirfd: Option<RawFd>, path: &P, mode: Mode) -> Result<()> {
528     let res = path.with_nix_path(|cstr| unsafe {
529         libc::mkfifoat(at_rawfd(dirfd), cstr.as_ptr(), mode.bits() as mode_t)
530     })?;
531 
532     Errno::result(res).map(drop)
533 }
534 
535 /// Creates a symbolic link at `path2` which points to `path1`.
536 ///
537 /// If `dirfd` has a value, then `path2` is relative to directory associated
538 /// with the file descriptor.
539 ///
540 /// If `dirfd` is `None`, then `path2` is relative to the current working
541 /// directory. This is identical to `libc::symlink(path1, path2)`.
542 ///
543 /// See also [symlinkat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/symlinkat.html).
544 #[cfg(not(target_os = "redox"))]
symlinkat<P1: ?Sized + NixPath, P2: ?Sized + NixPath>( path1: &P1, dirfd: Option<RawFd>, path2: &P2) -> Result<()>545 pub fn symlinkat<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
546     path1: &P1,
547     dirfd: Option<RawFd>,
548     path2: &P2) -> Result<()> {
549     let res =
550         path1.with_nix_path(|path1| {
551             path2.with_nix_path(|path2| {
552                 unsafe {
553                     libc::symlinkat(
554                         path1.as_ptr(),
555                         dirfd.unwrap_or(libc::AT_FDCWD),
556                         path2.as_ptr()
557                     )
558                 }
559             })
560         })??;
561     Errno::result(res).map(drop)
562 }
563 
564 // Double the buffer capacity up to limit. In case it already has
565 // reached the limit, return Errno::ERANGE.
reserve_double_buffer_size<T>(buf: &mut Vec<T>, limit: usize) -> Result<()>566 fn reserve_double_buffer_size<T>(buf: &mut Vec<T>, limit: usize) -> Result<()> {
567     use std::cmp::min;
568 
569     if buf.capacity() >= limit {
570         return Err(Error::from(Errno::ERANGE))
571     }
572 
573     let capacity = min(buf.capacity() * 2, limit);
574     buf.reserve(capacity);
575 
576     Ok(())
577 }
578 
579 /// Returns the current directory as a `PathBuf`
580 ///
581 /// Err is returned if the current user doesn't have the permission to read or search a component
582 /// of the current path.
583 ///
584 /// # Example
585 ///
586 /// ```rust
587 /// use nix::unistd;
588 ///
589 /// // assume that we are allowed to get current directory
590 /// let dir = unistd::getcwd().unwrap();
591 /// println!("The current directory is {:?}", dir);
592 /// ```
593 #[inline]
getcwd() -> Result<PathBuf>594 pub fn getcwd() -> Result<PathBuf> {
595     let mut buf = Vec::with_capacity(512);
596     loop {
597         unsafe {
598             let ptr = buf.as_mut_ptr() as *mut c_char;
599 
600             // The buffer must be large enough to store the absolute pathname plus
601             // a terminating null byte, or else null is returned.
602             // To safely handle this we start with a reasonable size (512 bytes)
603             // and double the buffer size upon every error
604             if !libc::getcwd(ptr, buf.capacity()).is_null() {
605                 let len = CStr::from_ptr(buf.as_ptr() as *const c_char).to_bytes().len();
606                 buf.set_len(len);
607                 buf.shrink_to_fit();
608                 return Ok(PathBuf::from(OsString::from_vec(buf)));
609             } else {
610                 let error = Errno::last();
611                 // ERANGE means buffer was too small to store directory name
612                 if error != Errno::ERANGE {
613                     return Err(Error::from(error));
614                 }
615             }
616 
617             // Trigger the internal buffer resizing logic.
618             reserve_double_buffer_size(&mut buf, PATH_MAX as usize)?;
619         }
620     }
621 }
622 
623 /// Computes the raw UID and GID values to pass to a `*chown` call.
624 // The cast is not unnecessary on all platforms.
625 #[allow(clippy::unnecessary_cast)]
chown_raw_ids(owner: Option<Uid>, group: Option<Gid>) -> (libc::uid_t, libc::gid_t)626 fn chown_raw_ids(owner: Option<Uid>, group: Option<Gid>) -> (libc::uid_t, libc::gid_t) {
627     // According to the POSIX specification, -1 is used to indicate that owner and group
628     // are not to be changed.  Since uid_t and gid_t are unsigned types, we have to wrap
629     // around to get -1.
630     let uid = owner.map(Into::into)
631         .unwrap_or_else(|| (0 as uid_t).wrapping_sub(1));
632     let gid = group.map(Into::into)
633         .unwrap_or_else(|| (0 as gid_t).wrapping_sub(1));
634     (uid, gid)
635 }
636 
637 /// Change the ownership of the file at `path` to be owned by the specified
638 /// `owner` (user) and `group` (see
639 /// [chown(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/chown.html)).
640 ///
641 /// The owner/group for the provided path name will not be modified if `None` is
642 /// provided for that argument.  Ownership change will be attempted for the path
643 /// only if `Some` owner/group is provided.
644 #[inline]
chown<P: ?Sized + NixPath>(path: &P, owner: Option<Uid>, group: Option<Gid>) -> Result<()>645 pub fn chown<P: ?Sized + NixPath>(path: &P, owner: Option<Uid>, group: Option<Gid>) -> Result<()> {
646     let res = path.with_nix_path(|cstr| {
647         let (uid, gid) = chown_raw_ids(owner, group);
648         unsafe { libc::chown(cstr.as_ptr(), uid, gid) }
649     })?;
650 
651     Errno::result(res).map(drop)
652 }
653 
654 /// Change the ownership of the file referred to by the open file descriptor `fd` to be owned by
655 /// the specified `owner` (user) and `group` (see
656 /// [fchown(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchown.html)).
657 ///
658 /// The owner/group for the provided file will not be modified if `None` is
659 /// provided for that argument.  Ownership change will be attempted for the path
660 /// only if `Some` owner/group is provided.
661 #[inline]
fchown(fd: RawFd, owner: Option<Uid>, group: Option<Gid>) -> Result<()>662 pub fn fchown(fd: RawFd, owner: Option<Uid>, group: Option<Gid>) -> Result<()> {
663     let (uid, gid) = chown_raw_ids(owner, group);
664     let res = unsafe { libc::fchown(fd, uid, gid) };
665     Errno::result(res).map(drop)
666 }
667 
668 /// Flags for `fchownat` function.
669 #[derive(Clone, Copy, Debug)]
670 pub enum FchownatFlags {
671     FollowSymlink,
672     NoFollowSymlink,
673 }
674 
675 /// Change the ownership of the file at `path` to be owned by the specified
676 /// `owner` (user) and `group`.
677 ///
678 /// The owner/group for the provided path name will not be modified if `None` is
679 /// provided for that argument.  Ownership change will be attempted for the path
680 /// only if `Some` owner/group is provided.
681 ///
682 /// The file to be changed is determined relative to the directory associated
683 /// with the file descriptor `dirfd` or the current working directory
684 /// if `dirfd` is `None`.
685 ///
686 /// If `flag` is `FchownatFlags::NoFollowSymlink` and `path` names a symbolic link,
687 /// then the mode of the symbolic link is changed.
688 ///
689 /// `fchownat(None, path, mode, FchownatFlags::NoFollowSymlink)` is identical to
690 /// a call `libc::lchown(path, mode)`.  That's why `lchmod` is unimplemented in
691 /// the `nix` crate.
692 ///
693 /// # References
694 ///
695 /// [fchownat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchownat.html).
696 #[cfg(not(target_os = "redox"))]
fchownat<P: ?Sized + NixPath>( dirfd: Option<RawFd>, path: &P, owner: Option<Uid>, group: Option<Gid>, flag: FchownatFlags, ) -> Result<()>697 pub fn fchownat<P: ?Sized + NixPath>(
698     dirfd: Option<RawFd>,
699     path: &P,
700     owner: Option<Uid>,
701     group: Option<Gid>,
702     flag: FchownatFlags,
703 ) -> Result<()> {
704     let atflag =
705         match flag {
706             FchownatFlags::FollowSymlink => AtFlags::empty(),
707             FchownatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW,
708         };
709     let res = path.with_nix_path(|cstr| unsafe {
710         let (uid, gid) = chown_raw_ids(owner, group);
711         libc::fchownat(at_rawfd(dirfd), cstr.as_ptr(), uid, gid,
712                        atflag.bits() as libc::c_int)
713     })?;
714 
715     Errno::result(res).map(drop)
716 }
717 
to_exec_array<S: AsRef<CStr>>(args: &[S]) -> Vec<*const c_char>718 fn to_exec_array<S: AsRef<CStr>>(args: &[S]) -> Vec<*const c_char> {
719     use std::iter::once;
720     args.iter().map(|s| s.as_ref().as_ptr()).chain(once(ptr::null())).collect()
721 }
722 
723 /// Replace the current process image with a new one (see
724 /// [exec(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)).
725 ///
726 /// See the `::nix::unistd::execve` system call for additional details.  `execv`
727 /// performs the same action but does not allow for customization of the
728 /// environment for the new process.
729 #[inline]
execv<S: AsRef<CStr>>(path: &CStr, argv: &[S]) -> Result<Infallible>730 pub fn execv<S: AsRef<CStr>>(path: &CStr, argv: &[S]) -> Result<Infallible> {
731     let args_p = to_exec_array(argv);
732 
733     unsafe {
734         libc::execv(path.as_ptr(), args_p.as_ptr())
735     };
736 
737     Err(Error::from(Errno::last()))
738 }
739 
740 
741 /// Replace the current process image with a new one (see
742 /// [execve(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)).
743 ///
744 /// The execve system call allows for another process to be "called" which will
745 /// replace the current process image.  That is, this process becomes the new
746 /// command that is run. On success, this function will not return. Instead,
747 /// the new program will run until it exits.
748 ///
749 /// `::nix::unistd::execv` and `::nix::unistd::execve` take as arguments a slice
750 /// of `::std::ffi::CString`s for `args` and `env` (for `execve`). Each element
751 /// in the `args` list is an argument to the new process. Each element in the
752 /// `env` list should be a string in the form "key=value".
753 #[inline]
execve<SA: AsRef<CStr>, SE: AsRef<CStr>>(path: &CStr, args: &[SA], env: &[SE]) -> Result<Infallible>754 pub fn execve<SA: AsRef<CStr>, SE: AsRef<CStr>>(path: &CStr, args: &[SA], env: &[SE]) -> Result<Infallible> {
755     let args_p = to_exec_array(args);
756     let env_p = to_exec_array(env);
757 
758     unsafe {
759         libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
760     };
761 
762     Err(Error::from(Errno::last()))
763 }
764 
765 /// Replace the current process image with a new one and replicate shell `PATH`
766 /// searching behavior (see
767 /// [exec(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)).
768 ///
769 /// See `::nix::unistd::execve` for additional details.  `execvp` behaves the
770 /// same as execv except that it will examine the `PATH` environment variables
771 /// for file names not specified with a leading slash.  For example, `execv`
772 /// would not work if "bash" was specified for the path argument, but `execvp`
773 /// would assuming that a bash executable was on the system `PATH`.
774 #[inline]
execvp<S: AsRef<CStr>>(filename: &CStr, args: &[S]) -> Result<Infallible>775 pub fn execvp<S: AsRef<CStr>>(filename: &CStr, args: &[S]) -> Result<Infallible> {
776     let args_p = to_exec_array(args);
777 
778     unsafe {
779         libc::execvp(filename.as_ptr(), args_p.as_ptr())
780     };
781 
782     Err(Error::from(Errno::last()))
783 }
784 
785 /// Replace the current process image with a new one and replicate shell `PATH`
786 /// searching behavior (see
787 /// [`execvpe(3)`](https://man7.org/linux/man-pages/man3/exec.3.html)).
788 ///
789 /// This functions like a combination of `execvp(2)` and `execve(2)` to pass an
790 /// environment and have a search path. See these two for additional
791 /// information.
792 #[cfg(any(target_os = "haiku",
793           target_os = "linux",
794           target_os = "openbsd"))]
execvpe<SA: AsRef<CStr>, SE: AsRef<CStr>>(filename: &CStr, args: &[SA], env: &[SE]) -> Result<Infallible>795 pub fn execvpe<SA: AsRef<CStr>, SE: AsRef<CStr>>(filename: &CStr, args: &[SA], env: &[SE]) -> Result<Infallible> {
796     let args_p = to_exec_array(args);
797     let env_p = to_exec_array(env);
798 
799     unsafe {
800         libc::execvpe(filename.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
801     };
802 
803     Err(Error::from(Errno::last()))
804 }
805 
806 /// Replace the current process image with a new one (see
807 /// [fexecve(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fexecve.html)).
808 ///
809 /// The `fexecve` function allows for another process to be "called" which will
810 /// replace the current process image.  That is, this process becomes the new
811 /// command that is run. On success, this function will not return. Instead,
812 /// the new program will run until it exits.
813 ///
814 /// This function is similar to `execve`, except that the program to be executed
815 /// is referenced as a file descriptor instead of a path.
816 // Note for NetBSD and OpenBSD: although rust-lang/libc includes it (under
817 // unix/bsd/netbsdlike/) fexecve is not currently implemented on NetBSD nor on
818 // OpenBSD.
819 #[cfg(any(target_os = "android",
820           target_os = "linux",
821           target_os = "freebsd"))]
822 #[inline]
fexecve<SA: AsRef<CStr> ,SE: AsRef<CStr>>(fd: RawFd, args: &[SA], env: &[SE]) -> Result<Infallible>823 pub fn fexecve<SA: AsRef<CStr> ,SE: AsRef<CStr>>(fd: RawFd, args: &[SA], env: &[SE]) -> Result<Infallible> {
824     let args_p = to_exec_array(args);
825     let env_p = to_exec_array(env);
826 
827     unsafe {
828         libc::fexecve(fd, args_p.as_ptr(), env_p.as_ptr())
829     };
830 
831     Err(Error::from(Errno::last()))
832 }
833 
834 /// Execute program relative to a directory file descriptor (see
835 /// [execveat(2)](https://man7.org/linux/man-pages/man2/execveat.2.html)).
836 ///
837 /// The `execveat` function allows for another process to be "called" which will
838 /// replace the current process image.  That is, this process becomes the new
839 /// command that is run. On success, this function will not return. Instead,
840 /// the new program will run until it exits.
841 ///
842 /// This function is similar to `execve`, except that the program to be executed
843 /// is referenced as a file descriptor to the base directory plus a path.
844 #[cfg(any(target_os = "android", target_os = "linux"))]
845 #[inline]
execveat<SA: AsRef<CStr>,SE: AsRef<CStr>>(dirfd: RawFd, pathname: &CStr, args: &[SA], env: &[SE], flags: super::fcntl::AtFlags) -> Result<Infallible>846 pub fn execveat<SA: AsRef<CStr>,SE: AsRef<CStr>>(dirfd: RawFd, pathname: &CStr, args: &[SA],
847                 env: &[SE], flags: super::fcntl::AtFlags) -> Result<Infallible> {
848     let args_p = to_exec_array(args);
849     let env_p = to_exec_array(env);
850 
851     unsafe {
852         libc::syscall(libc::SYS_execveat, dirfd, pathname.as_ptr(),
853                       args_p.as_ptr(), env_p.as_ptr(), flags);
854     };
855 
856     Err(Error::from(Errno::last()))
857 }
858 
859 /// Daemonize this process by detaching from the controlling terminal (see
860 /// [daemon(3)](https://man7.org/linux/man-pages/man3/daemon.3.html)).
861 ///
862 /// When a process is launched it is typically associated with a parent and it,
863 /// in turn, by its controlling terminal/process.  In order for a process to run
864 /// in the "background" it must daemonize itself by detaching itself.  Under
865 /// posix, this is done by doing the following:
866 ///
867 /// 1. Parent process (this one) forks
868 /// 2. Parent process exits
869 /// 3. Child process continues to run.
870 ///
871 /// `nochdir`:
872 ///
873 /// * `nochdir = true`: The current working directory after daemonizing will
874 ///    be the current working directory.
875 /// *  `nochdir = false`: The current working directory after daemonizing will
876 ///    be the root direcory, `/`.
877 ///
878 /// `noclose`:
879 ///
880 /// * `noclose = true`: The process' current stdin, stdout, and stderr file
881 ///   descriptors will remain identical after daemonizing.
882 /// * `noclose = false`: The process' stdin, stdout, and stderr will point to
883 ///   `/dev/null` after daemonizing.
884 #[cfg(any(target_os = "android",
885           target_os = "dragonfly",
886           target_os = "freebsd",
887           target_os = "illumos",
888           target_os = "linux",
889           target_os = "netbsd",
890           target_os = "openbsd",
891           target_os = "solaris"))]
daemon(nochdir: bool, noclose: bool) -> Result<()>892 pub fn daemon(nochdir: bool, noclose: bool) -> Result<()> {
893     let res = unsafe { libc::daemon(nochdir as c_int, noclose as c_int) };
894     Errno::result(res).map(drop)
895 }
896 
897 /// Set the system host name (see
898 /// [sethostname(2)](https://man7.org/linux/man-pages/man2/gethostname.2.html)).
899 ///
900 /// Given a name, attempt to update the system host name to the given string.
901 /// On some systems, the host name is limited to as few as 64 bytes.  An error
902 /// will be return if the name is not valid or the current process does not have
903 /// permissions to update the host name.
904 #[cfg(not(target_os = "redox"))]
sethostname<S: AsRef<OsStr>>(name: S) -> Result<()>905 pub fn sethostname<S: AsRef<OsStr>>(name: S) -> Result<()> {
906     // Handle some differences in type of the len arg across platforms.
907     cfg_if! {
908         if #[cfg(any(target_os = "dragonfly",
909                      target_os = "freebsd",
910                      target_os = "illumos",
911                      target_os = "ios",
912                      target_os = "macos",
913                      target_os = "solaris", ))] {
914             type sethostname_len_t = c_int;
915         } else {
916             type sethostname_len_t = size_t;
917         }
918     }
919     let ptr = name.as_ref().as_bytes().as_ptr() as *const c_char;
920     let len = name.as_ref().len() as sethostname_len_t;
921 
922     let res = unsafe { libc::sethostname(ptr, len) };
923     Errno::result(res).map(drop)
924 }
925 
926 /// Get the host name and store it in the provided buffer, returning a pointer
927 /// the `CStr` in that buffer on success (see
928 /// [gethostname(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/gethostname.html)).
929 ///
930 /// This function call attempts to get the host name for the running system and
931 /// store it in a provided buffer.  The buffer will be populated with bytes up
932 /// to the length of the provided slice including a NUL terminating byte.  If
933 /// the hostname is longer than the length provided, no error will be provided.
934 /// The posix specification does not specify whether implementations will
935 /// null-terminate in this case, but the nix implementation will ensure that the
936 /// buffer is null terminated in this case.
937 ///
938 /// ```no_run
939 /// use nix::unistd;
940 ///
941 /// let mut buf = [0u8; 64];
942 /// let hostname_cstr = unistd::gethostname(&mut buf).expect("Failed getting hostname");
943 /// let hostname = hostname_cstr.to_str().expect("Hostname wasn't valid UTF-8");
944 /// println!("Hostname: {}", hostname);
945 /// ```
gethostname(buffer: &mut [u8]) -> Result<&CStr>946 pub fn gethostname(buffer: &mut [u8]) -> Result<&CStr> {
947     let ptr = buffer.as_mut_ptr() as *mut c_char;
948     let len = buffer.len() as size_t;
949 
950     let res = unsafe { libc::gethostname(ptr, len) };
951     Errno::result(res).map(|_| {
952         buffer[len - 1] = 0; // ensure always null-terminated
953         unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) }
954     })
955 }
956 
957 /// Close a raw file descriptor
958 ///
959 /// Be aware that many Rust types implicitly close-on-drop, including
960 /// `std::fs::File`.  Explicitly closing them with this method too can result in
961 /// a double-close condition, which can cause confusing `EBADF` errors in
962 /// seemingly unrelated code.  Caveat programmer.  See also
963 /// [close(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/close.html).
964 ///
965 /// # Examples
966 ///
967 /// ```no_run
968 /// use std::os::unix::io::AsRawFd;
969 /// use nix::unistd::close;
970 ///
971 /// let f = tempfile::tempfile().unwrap();
972 /// close(f.as_raw_fd()).unwrap();   // Bad!  f will also close on drop!
973 /// ```
974 ///
975 /// ```rust
976 /// use std::os::unix::io::IntoRawFd;
977 /// use nix::unistd::close;
978 ///
979 /// let f = tempfile::tempfile().unwrap();
980 /// close(f.into_raw_fd()).unwrap(); // Good.  into_raw_fd consumes f
981 /// ```
close(fd: RawFd) -> Result<()>982 pub fn close(fd: RawFd) -> Result<()> {
983     let res = unsafe { libc::close(fd) };
984     Errno::result(res).map(drop)
985 }
986 
987 /// Read from a raw file descriptor.
988 ///
989 /// See also [read(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html)
read(fd: RawFd, buf: &mut [u8]) -> Result<usize>990 pub fn read(fd: RawFd, buf: &mut [u8]) -> Result<usize> {
991     let res = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t) };
992 
993     Errno::result(res).map(|r| r as usize)
994 }
995 
996 /// Write to a raw file descriptor.
997 ///
998 /// See also [write(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html)
write(fd: RawFd, buf: &[u8]) -> Result<usize>999 pub fn write(fd: RawFd, buf: &[u8]) -> Result<usize> {
1000     let res = unsafe { libc::write(fd, buf.as_ptr() as *const c_void, buf.len() as size_t) };
1001 
1002     Errno::result(res).map(|r| r as usize)
1003 }
1004 
1005 /// Directive that tells [`lseek`] and [`lseek64`] what the offset is relative to.
1006 ///
1007 /// [`lseek`]: ./fn.lseek.html
1008 /// [`lseek64`]: ./fn.lseek64.html
1009 #[repr(i32)]
1010 #[derive(Clone, Copy, Debug)]
1011 pub enum Whence {
1012     /// Specify an offset relative to the start of the file.
1013     SeekSet = libc::SEEK_SET,
1014     /// Specify an offset relative to the current file location.
1015     SeekCur = libc::SEEK_CUR,
1016     /// Specify an offset relative to the end of the file.
1017     SeekEnd = libc::SEEK_END,
1018     /// Specify an offset relative to the next location in the file greater than or
1019     /// equal to offset that contains some data. If offset points to
1020     /// some data, then the file offset is set to offset.
1021     #[cfg(any(target_os = "dragonfly",
1022               target_os = "freebsd",
1023               target_os = "illumos",
1024               target_os = "linux",
1025               target_os = "solaris"))]
1026     SeekData = libc::SEEK_DATA,
1027     /// Specify an offset relative to the next hole in the file greater than
1028     /// or equal to offset. If offset points into the middle of a hole, then
1029     /// the file offset should be set to offset. If there is no hole past offset,
1030     /// then the file offset should be adjusted to the end of the file (i.e., there
1031     /// is an implicit hole at the end of any file).
1032     #[cfg(any(target_os = "dragonfly",
1033               target_os = "freebsd",
1034               target_os = "illumos",
1035               target_os = "linux",
1036               target_os = "solaris"))]
1037     SeekHole = libc::SEEK_HOLE
1038 }
1039 
1040 /// Move the read/write file offset.
1041 ///
1042 /// See also [lseek(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/lseek.html)
lseek(fd: RawFd, offset: off_t, whence: Whence) -> Result<off_t>1043 pub fn lseek(fd: RawFd, offset: off_t, whence: Whence) -> Result<off_t> {
1044     let res = unsafe { libc::lseek(fd, offset, whence as i32) };
1045 
1046     Errno::result(res).map(|r| r as off_t)
1047 }
1048 
1049 #[cfg(any(target_os = "linux", target_os = "android"))]
lseek64(fd: RawFd, offset: libc::off64_t, whence: Whence) -> Result<libc::off64_t>1050 pub fn lseek64(fd: RawFd, offset: libc::off64_t, whence: Whence) -> Result<libc::off64_t> {
1051     let res = unsafe { libc::lseek64(fd, offset, whence as i32) };
1052 
1053     Errno::result(res).map(|r| r as libc::off64_t)
1054 }
1055 
1056 /// Create an interprocess channel.
1057 ///
1058 /// See also [pipe(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pipe.html)
pipe() -> std::result::Result<(RawFd, RawFd), Error>1059 pub fn pipe() -> std::result::Result<(RawFd, RawFd), Error> {
1060     unsafe {
1061         let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit();
1062 
1063         let res = libc::pipe(fds.as_mut_ptr() as *mut c_int);
1064 
1065         Error::result(res)?;
1066 
1067         Ok((fds.assume_init()[0], fds.assume_init()[1]))
1068     }
1069 }
1070 
1071 /// Like `pipe`, but allows setting certain file descriptor flags.
1072 ///
1073 /// The following flags are supported, and will be set atomically as the pipe is
1074 /// created:
1075 ///
1076 /// `O_CLOEXEC`:    Set the close-on-exec flag for the new file descriptors.
1077 #[cfg_attr(target_os = "linux", doc = "`O_DIRECT`: Create a pipe that performs I/O in \"packet\" mode.  ")]
1078 #[cfg_attr(target_os = "netbsd", doc = "`O_NOSIGPIPE`: Return `EPIPE` instead of raising `SIGPIPE`.  ")]
1079 /// `O_NONBLOCK`:   Set the non-blocking flag for the ends of the pipe.
1080 ///
1081 /// See also [pipe(2)](https://man7.org/linux/man-pages/man2/pipe.2.html)
1082 #[cfg(any(target_os = "android",
1083           target_os = "dragonfly",
1084           target_os = "emscripten",
1085           target_os = "freebsd",
1086           target_os = "illumos",
1087           target_os = "linux",
1088           target_os = "redox",
1089           target_os = "netbsd",
1090           target_os = "openbsd",
1091           target_os = "solaris"))]
pipe2(flags: OFlag) -> Result<(RawFd, RawFd)>1092 pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> {
1093     let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit();
1094 
1095     let res = unsafe {
1096         libc::pipe2(fds.as_mut_ptr() as *mut c_int, flags.bits())
1097     };
1098 
1099     Errno::result(res)?;
1100 
1101     unsafe { Ok((fds.assume_init()[0], fds.assume_init()[1])) }
1102 }
1103 
1104 /// Truncate a file to a specified length
1105 ///
1106 /// See also
1107 /// [truncate(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/truncate.html)
1108 #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))]
truncate<P: ?Sized + NixPath>(path: &P, len: off_t) -> Result<()>1109 pub fn truncate<P: ?Sized + NixPath>(path: &P, len: off_t) -> Result<()> {
1110     let res = path.with_nix_path(|cstr| {
1111         unsafe {
1112             libc::truncate(cstr.as_ptr(), len)
1113         }
1114     })?;
1115 
1116     Errno::result(res).map(drop)
1117 }
1118 
1119 /// Truncate a file to a specified length
1120 ///
1121 /// See also
1122 /// [ftruncate(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html)
ftruncate(fd: RawFd, len: off_t) -> Result<()>1123 pub fn ftruncate(fd: RawFd, len: off_t) -> Result<()> {
1124     Errno::result(unsafe { libc::ftruncate(fd, len) }).map(drop)
1125 }
1126 
isatty(fd: RawFd) -> Result<bool>1127 pub fn isatty(fd: RawFd) -> Result<bool> {
1128     unsafe {
1129         // ENOTTY means `fd` is a valid file descriptor, but not a TTY, so
1130         // we return `Ok(false)`
1131         if libc::isatty(fd) == 1 {
1132             Ok(true)
1133         } else {
1134             match Errno::last() {
1135                 Errno::ENOTTY => Ok(false),
1136                 err => Err(Error::from(err)),
1137             }
1138         }
1139     }
1140 }
1141 
1142 /// Flags for `linkat` function.
1143 #[derive(Clone, Copy, Debug)]
1144 pub enum LinkatFlags {
1145     SymlinkFollow,
1146     NoSymlinkFollow,
1147 }
1148 
1149 /// Link one file to another file
1150 ///
1151 /// Creates a new link (directory entry) at `newpath` for the existing file at `oldpath`. In the
1152 /// case of a relative `oldpath`, the path is interpreted relative to the directory associated
1153 /// with file descriptor `olddirfd` instead of the current working directory and similiarly for
1154 /// `newpath` and file descriptor `newdirfd`. In case `flag` is LinkatFlags::SymlinkFollow and
1155 /// `oldpath` names a symoblic link, a new link for the target of the symbolic link is created.
1156 /// If either `olddirfd` or `newdirfd` is `None`, `AT_FDCWD` is used respectively where `oldpath`
1157 /// and/or `newpath` is then interpreted relative to the current working directory of the calling
1158 /// process. If either `oldpath` or `newpath` is absolute, then `dirfd` is ignored.
1159 ///
1160 /// # References
1161 /// See also [linkat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/linkat.html)
1162 #[cfg(not(target_os = "redox"))] // RedoxFS does not support symlinks yet
linkat<P: ?Sized + NixPath>( olddirfd: Option<RawFd>, oldpath: &P, newdirfd: Option<RawFd>, newpath: &P, flag: LinkatFlags, ) -> Result<()>1163 pub fn linkat<P: ?Sized + NixPath>(
1164     olddirfd: Option<RawFd>,
1165     oldpath: &P,
1166     newdirfd: Option<RawFd>,
1167     newpath: &P,
1168     flag: LinkatFlags,
1169 ) -> Result<()> {
1170 
1171     let atflag =
1172         match flag {
1173             LinkatFlags::SymlinkFollow => AtFlags::AT_SYMLINK_FOLLOW,
1174             LinkatFlags::NoSymlinkFollow => AtFlags::empty(),
1175         };
1176 
1177     let res =
1178         oldpath.with_nix_path(|oldcstr| {
1179             newpath.with_nix_path(|newcstr| {
1180             unsafe {
1181                 libc::linkat(
1182                     at_rawfd(olddirfd),
1183                     oldcstr.as_ptr(),
1184                     at_rawfd(newdirfd),
1185                     newcstr.as_ptr(),
1186                     atflag.bits() as libc::c_int
1187                     )
1188                 }
1189             })
1190         })??;
1191     Errno::result(res).map(drop)
1192 }
1193 
1194 
1195 /// Remove a directory entry
1196 ///
1197 /// See also [unlink(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/unlink.html)
unlink<P: ?Sized + NixPath>(path: &P) -> Result<()>1198 pub fn unlink<P: ?Sized + NixPath>(path: &P) -> Result<()> {
1199     let res = path.with_nix_path(|cstr| {
1200         unsafe {
1201             libc::unlink(cstr.as_ptr())
1202         }
1203     })?;
1204     Errno::result(res).map(drop)
1205 }
1206 
1207 /// Flags for `unlinkat` function.
1208 #[derive(Clone, Copy, Debug)]
1209 pub enum UnlinkatFlags {
1210     RemoveDir,
1211     NoRemoveDir,
1212 }
1213 
1214 /// Remove a directory entry
1215 ///
1216 /// In the case of a relative path, the directory entry to be removed is determined relative to
1217 /// the directory associated with the file descriptor `dirfd` or the current working directory
1218 /// if `dirfd` is `None`. In the case of an absolute `path` `dirfd` is ignored. If `flag` is
1219 /// `UnlinkatFlags::RemoveDir` then removal of the directory entry specified by `dirfd` and `path`
1220 /// is performed.
1221 ///
1222 /// # References
1223 /// See also [unlinkat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/unlinkat.html)
1224 #[cfg(not(target_os = "redox"))]
unlinkat<P: ?Sized + NixPath>( dirfd: Option<RawFd>, path: &P, flag: UnlinkatFlags, ) -> Result<()>1225 pub fn unlinkat<P: ?Sized + NixPath>(
1226     dirfd: Option<RawFd>,
1227     path: &P,
1228     flag: UnlinkatFlags,
1229 ) -> Result<()> {
1230     let atflag =
1231         match flag {
1232             UnlinkatFlags::RemoveDir => AtFlags::AT_REMOVEDIR,
1233             UnlinkatFlags::NoRemoveDir => AtFlags::empty(),
1234         };
1235     let res = path.with_nix_path(|cstr| {
1236         unsafe {
1237             libc::unlinkat(at_rawfd(dirfd), cstr.as_ptr(), atflag.bits() as libc::c_int)
1238         }
1239     })?;
1240     Errno::result(res).map(drop)
1241 }
1242 
1243 
1244 #[inline]
1245 #[cfg(not(target_os = "fuchsia"))]
chroot<P: ?Sized + NixPath>(path: &P) -> Result<()>1246 pub fn chroot<P: ?Sized + NixPath>(path: &P) -> Result<()> {
1247     let res = path.with_nix_path(|cstr| {
1248         unsafe { libc::chroot(cstr.as_ptr()) }
1249     })?;
1250 
1251     Errno::result(res).map(drop)
1252 }
1253 
1254 /// Commit filesystem caches to disk
1255 ///
1256 /// See also [sync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sync.html)
1257 #[cfg(any(
1258     target_os = "dragonfly",
1259     target_os = "freebsd",
1260     target_os = "linux",
1261     target_os = "netbsd",
1262     target_os = "openbsd"
1263 ))]
sync()1264 pub fn sync() {
1265     unsafe { libc::sync() };
1266 }
1267 
1268 /// Synchronize changes to a file
1269 ///
1270 /// See also [fsync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fsync.html)
1271 #[inline]
fsync(fd: RawFd) -> Result<()>1272 pub fn fsync(fd: RawFd) -> Result<()> {
1273     let res = unsafe { libc::fsync(fd) };
1274 
1275     Errno::result(res).map(drop)
1276 }
1277 
1278 /// Synchronize the data of a file
1279 ///
1280 /// See also
1281 /// [fdatasync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html)
1282 // `fdatasync(2) is in POSIX, but in libc it is only defined in `libc::notbsd`.
1283 // TODO: exclude only Apple systems after https://github.com/rust-lang/libc/pull/211
1284 #[cfg(any(target_os = "linux",
1285           target_os = "android",
1286           target_os = "emscripten",
1287           target_os = "illumos",
1288           target_os = "solaris"))]
1289 #[inline]
fdatasync(fd: RawFd) -> Result<()>1290 pub fn fdatasync(fd: RawFd) -> Result<()> {
1291     let res = unsafe { libc::fdatasync(fd) };
1292 
1293     Errno::result(res).map(drop)
1294 }
1295 
1296 /// Get a real user ID
1297 ///
1298 /// See also [getuid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getuid.html)
1299 // POSIX requires that getuid is always successful, so no need to check return
1300 // value or errno.
1301 #[inline]
getuid() -> Uid1302 pub fn getuid() -> Uid {
1303     Uid(unsafe { libc::getuid() })
1304 }
1305 
1306 /// Get the effective user ID
1307 ///
1308 /// See also [geteuid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/geteuid.html)
1309 // POSIX requires that geteuid is always successful, so no need to check return
1310 // value or errno.
1311 #[inline]
geteuid() -> Uid1312 pub fn geteuid() -> Uid {
1313     Uid(unsafe { libc::geteuid() })
1314 }
1315 
1316 /// Get the real group ID
1317 ///
1318 /// See also [getgid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getgid.html)
1319 // POSIX requires that getgid is always successful, so no need to check return
1320 // value or errno.
1321 #[inline]
getgid() -> Gid1322 pub fn getgid() -> Gid {
1323     Gid(unsafe { libc::getgid() })
1324 }
1325 
1326 /// Get the effective group ID
1327 ///
1328 /// See also [getegid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getegid.html)
1329 // POSIX requires that getegid is always successful, so no need to check return
1330 // value or errno.
1331 #[inline]
getegid() -> Gid1332 pub fn getegid() -> Gid {
1333     Gid(unsafe { libc::getegid() })
1334 }
1335 
1336 /// Set the effective user ID
1337 ///
1338 /// See also [seteuid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/seteuid.html)
1339 #[inline]
seteuid(euid: Uid) -> Result<()>1340 pub fn seteuid(euid: Uid) -> Result<()> {
1341     let res = unsafe { libc::seteuid(euid.into()) };
1342 
1343     Errno::result(res).map(drop)
1344 }
1345 
1346 /// Set the effective group ID
1347 ///
1348 /// See also [setegid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setegid.html)
1349 #[inline]
setegid(egid: Gid) -> Result<()>1350 pub fn setegid(egid: Gid) -> Result<()> {
1351     let res = unsafe { libc::setegid(egid.into()) };
1352 
1353     Errno::result(res).map(drop)
1354 }
1355 
1356 /// Set the user ID
1357 ///
1358 /// See also [setuid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setuid.html)
1359 #[inline]
setuid(uid: Uid) -> Result<()>1360 pub fn setuid(uid: Uid) -> Result<()> {
1361     let res = unsafe { libc::setuid(uid.into()) };
1362 
1363     Errno::result(res).map(drop)
1364 }
1365 
1366 /// Set the group ID
1367 ///
1368 /// See also [setgid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setgid.html)
1369 #[inline]
setgid(gid: Gid) -> Result<()>1370 pub fn setgid(gid: Gid) -> Result<()> {
1371     let res = unsafe { libc::setgid(gid.into()) };
1372 
1373     Errno::result(res).map(drop)
1374 }
1375 
1376 /// Set the user identity used for filesystem checks per-thread.
1377 /// On both success and failure, this call returns the previous filesystem user
1378 /// ID of the caller.
1379 ///
1380 /// See also [setfsuid(2)](https://man7.org/linux/man-pages/man2/setfsuid.2.html)
1381 #[cfg(any(target_os = "linux", target_os = "android"))]
setfsuid(uid: Uid) -> Uid1382 pub fn setfsuid(uid: Uid) -> Uid {
1383     let prev_fsuid = unsafe { libc::setfsuid(uid.into()) };
1384     Uid::from_raw(prev_fsuid as uid_t)
1385 }
1386 
1387 /// Set the group identity used for filesystem checks per-thread.
1388 /// On both success and failure, this call returns the previous filesystem group
1389 /// ID of the caller.
1390 ///
1391 /// See also [setfsgid(2)](https://man7.org/linux/man-pages/man2/setfsgid.2.html)
1392 #[cfg(any(target_os = "linux", target_os = "android"))]
setfsgid(gid: Gid) -> Gid1393 pub fn setfsgid(gid: Gid) -> Gid {
1394     let prev_fsgid = unsafe { libc::setfsgid(gid.into()) };
1395     Gid::from_raw(prev_fsgid as gid_t)
1396 }
1397 
1398 /// Get the list of supplementary group IDs of the calling process.
1399 ///
1400 /// [Further reading](https://pubs.opengroup.org/onlinepubs/009695399/functions/getgroups.html)
1401 ///
1402 /// **Note:** This function is not available for Apple platforms. On those
1403 /// platforms, checking group membership should be achieved via communication
1404 /// with the `opendirectoryd` service.
1405 #[cfg(not(any(target_os = "ios", target_os = "macos")))]
getgroups() -> Result<Vec<Gid>>1406 pub fn getgroups() -> Result<Vec<Gid>> {
1407     // First get the maximum number of groups. The value returned
1408     // shall always be greater than or equal to one and less than or
1409     // equal to the value of {NGROUPS_MAX} + 1.
1410     let ngroups_max = match sysconf(SysconfVar::NGROUPS_MAX) {
1411         Ok(Some(n)) => (n + 1) as usize,
1412         Ok(None) | Err(_) => <usize>::max_value(),
1413     };
1414 
1415     // Next, get the number of groups so we can size our Vec
1416     let ngroups = unsafe { libc::getgroups(0, ptr::null_mut()) };
1417 
1418     // Now actually get the groups. We try multiple times in case the number of
1419     // groups has changed since the first call to getgroups() and the buffer is
1420     // now too small.
1421     let mut groups = Vec::<Gid>::with_capacity(Errno::result(ngroups)? as usize);
1422     loop {
1423         // FIXME: On the platforms we currently support, the `Gid` struct has
1424         // the same representation in memory as a bare `gid_t`. This is not
1425         // necessarily the case on all Rust platforms, though. See RFC 1785.
1426         let ngroups = unsafe {
1427             libc::getgroups(groups.capacity() as c_int, groups.as_mut_ptr() as *mut gid_t)
1428         };
1429 
1430         match Errno::result(ngroups) {
1431             Ok(s) => {
1432                 unsafe { groups.set_len(s as usize) };
1433                 return Ok(groups);
1434             },
1435             Err(Errno::EINVAL) => {
1436                 // EINVAL indicates that the buffer size was too
1437                 // small, resize it up to ngroups_max as limit.
1438                 reserve_double_buffer_size(&mut groups, ngroups_max)
1439                     .or(Err(Error::from(Errno::EINVAL)))?;
1440             },
1441             Err(e) => return Err(e)
1442         }
1443     }
1444 }
1445 
1446 /// Set the list of supplementary group IDs for the calling process.
1447 ///
1448 /// [Further reading](https://man7.org/linux/man-pages/man2/getgroups.2.html)
1449 ///
1450 /// **Note:** This function is not available for Apple platforms. On those
1451 /// platforms, group membership management should be achieved via communication
1452 /// with the `opendirectoryd` service.
1453 ///
1454 /// # Examples
1455 ///
1456 /// `setgroups` can be used when dropping privileges from the root user to a
1457 /// specific user and group. For example, given the user `www-data` with UID
1458 /// `33` and the group `backup` with the GID `34`, one could switch the user as
1459 /// follows:
1460 ///
1461 /// ```rust,no_run
1462 /// # use std::error::Error;
1463 /// # use nix::unistd::*;
1464 /// #
1465 /// # fn try_main() -> Result<(), Box<Error>> {
1466 /// let uid = Uid::from_raw(33);
1467 /// let gid = Gid::from_raw(34);
1468 /// setgroups(&[gid])?;
1469 /// setgid(gid)?;
1470 /// setuid(uid)?;
1471 /// #
1472 /// #     Ok(())
1473 /// # }
1474 /// #
1475 /// # try_main().unwrap();
1476 /// ```
1477 #[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))]
setgroups(groups: &[Gid]) -> Result<()>1478 pub fn setgroups(groups: &[Gid]) -> Result<()> {
1479     cfg_if! {
1480         if #[cfg(any(target_os = "dragonfly",
1481                      target_os = "freebsd",
1482                      target_os = "illumos",
1483                      target_os = "ios",
1484                      target_os = "macos",
1485                      target_os = "netbsd",
1486                      target_os = "illumos",
1487                      target_os = "openbsd"))] {
1488             type setgroups_ngroups_t = c_int;
1489         } else {
1490             type setgroups_ngroups_t = size_t;
1491         }
1492     }
1493     // FIXME: On the platforms we currently support, the `Gid` struct has the
1494     // same representation in memory as a bare `gid_t`. This is not necessarily
1495     // the case on all Rust platforms, though. See RFC 1785.
1496     let res = unsafe {
1497         libc::setgroups(groups.len() as setgroups_ngroups_t, groups.as_ptr() as *const gid_t)
1498     };
1499 
1500     Errno::result(res).map(drop)
1501 }
1502 
1503 /// Calculate the supplementary group access list.
1504 ///
1505 /// Gets the group IDs of all groups that `user` is a member of. The additional
1506 /// group `group` is also added to the list.
1507 ///
1508 /// [Further reading](https://man7.org/linux/man-pages/man3/getgrouplist.3.html)
1509 ///
1510 /// **Note:** This function is not available for Apple platforms. On those
1511 /// platforms, checking group membership should be achieved via communication
1512 /// with the `opendirectoryd` service.
1513 ///
1514 /// # Errors
1515 ///
1516 /// Although the `getgrouplist()` call does not return any specific
1517 /// errors on any known platforms, this implementation will return a system
1518 /// error of `EINVAL` if the number of groups to be fetched exceeds the
1519 /// `NGROUPS_MAX` sysconf value. This mimics the behaviour of `getgroups()`
1520 /// and `setgroups()`. Additionally, while some implementations will return a
1521 /// partial list of groups when `NGROUPS_MAX` is exceeded, this implementation
1522 /// will only ever return the complete list or else an error.
1523 #[cfg(not(any(target_os = "illumos",
1524               target_os = "ios",
1525               target_os = "macos",
1526               target_os = "redox")))]
getgrouplist(user: &CStr, group: Gid) -> Result<Vec<Gid>>1527 pub fn getgrouplist(user: &CStr, group: Gid) -> Result<Vec<Gid>> {
1528     let ngroups_max = match sysconf(SysconfVar::NGROUPS_MAX) {
1529         Ok(Some(n)) => n as c_int,
1530         Ok(None) | Err(_) => <c_int>::max_value(),
1531     };
1532     use std::cmp::min;
1533     let mut ngroups = min(ngroups_max, 8);
1534     let mut groups = Vec::<Gid>::with_capacity(ngroups as usize);
1535     cfg_if! {
1536         if #[cfg(any(target_os = "ios", target_os = "macos"))] {
1537             type getgrouplist_group_t = c_int;
1538         } else {
1539             type getgrouplist_group_t = gid_t;
1540         }
1541     }
1542     let gid: gid_t = group.into();
1543     loop {
1544         let ret = unsafe {
1545             libc::getgrouplist(user.as_ptr(),
1546                                gid as getgrouplist_group_t,
1547                                groups.as_mut_ptr() as *mut getgrouplist_group_t,
1548                                &mut ngroups)
1549         };
1550 
1551         // BSD systems only return 0 or -1, Linux returns ngroups on success.
1552         if ret >= 0 {
1553             unsafe { groups.set_len(ngroups as usize) };
1554             return Ok(groups);
1555         } else if ret == -1 {
1556             // Returns -1 if ngroups is too small, but does not set errno.
1557             // BSD systems will still fill the groups buffer with as many
1558             // groups as possible, but Linux manpages do not mention this
1559             // behavior.
1560             reserve_double_buffer_size(&mut groups, ngroups_max as usize)
1561                 .map_err(|_| Error::from(Errno::EINVAL))?;
1562         }
1563     }
1564 }
1565 
1566 /// Initialize the supplementary group access list.
1567 ///
1568 /// Sets the supplementary group IDs for the calling process using all groups
1569 /// that `user` is a member of. The additional group `group` is also added to
1570 /// the list.
1571 ///
1572 /// [Further reading](https://man7.org/linux/man-pages/man3/initgroups.3.html)
1573 ///
1574 /// **Note:** This function is not available for Apple platforms. On those
1575 /// platforms, group membership management should be achieved via communication
1576 /// with the `opendirectoryd` service.
1577 ///
1578 /// # Examples
1579 ///
1580 /// `initgroups` can be used when dropping privileges from the root user to
1581 /// another user. For example, given the user `www-data`, we could look up the
1582 /// UID and GID for the user in the system's password database (usually found
1583 /// in `/etc/passwd`). If the `www-data` user's UID and GID were `33` and `33`,
1584 /// respectively, one could switch the user as follows:
1585 ///
1586 /// ```rust,no_run
1587 /// # use std::error::Error;
1588 /// # use std::ffi::CString;
1589 /// # use nix::unistd::*;
1590 /// #
1591 /// # fn try_main() -> Result<(), Box<Error>> {
1592 /// let user = CString::new("www-data").unwrap();
1593 /// let uid = Uid::from_raw(33);
1594 /// let gid = Gid::from_raw(33);
1595 /// initgroups(&user, gid)?;
1596 /// setgid(gid)?;
1597 /// setuid(uid)?;
1598 /// #
1599 /// #     Ok(())
1600 /// # }
1601 /// #
1602 /// # try_main().unwrap();
1603 /// ```
1604 #[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))]
initgroups(user: &CStr, group: Gid) -> Result<()>1605 pub fn initgroups(user: &CStr, group: Gid) -> Result<()> {
1606     cfg_if! {
1607         if #[cfg(any(target_os = "ios", target_os = "macos"))] {
1608             type initgroups_group_t = c_int;
1609         } else {
1610             type initgroups_group_t = gid_t;
1611         }
1612     }
1613     let gid: gid_t = group.into();
1614     let res = unsafe { libc::initgroups(user.as_ptr(), gid as initgroups_group_t) };
1615 
1616     Errno::result(res).map(drop)
1617 }
1618 
1619 /// Suspend the thread until a signal is received.
1620 ///
1621 /// See also [pause(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pause.html).
1622 #[inline]
1623 #[cfg(not(target_os = "redox"))]
pause()1624 pub fn pause() {
1625     unsafe { libc::pause() };
1626 }
1627 
1628 pub mod alarm {
1629     //! Alarm signal scheduling.
1630     //!
1631     //! Scheduling an alarm will trigger a `SIGALRM` signal when the time has
1632     //! elapsed, which has to be caught, because the default action for the
1633     //! signal is to terminate the program. This signal also can't be ignored
1634     //! because the system calls like `pause` will not be interrupted, see the
1635     //! second example below.
1636     //!
1637     //! # Examples
1638     //!
1639     //! Canceling an alarm:
1640     //!
1641     //! ```
1642     //! use nix::unistd::alarm;
1643     //!
1644     //! // Set an alarm for 60 seconds from now.
1645     //! alarm::set(60);
1646     //!
1647     //! // Cancel the above set alarm, which returns the number of seconds left
1648     //! // of the previously set alarm.
1649     //! assert_eq!(alarm::cancel(), Some(60));
1650     //! ```
1651     //!
1652     //! Scheduling an alarm and waiting for the signal:
1653     //!
1654 #![cfg_attr(target_os = "redox", doc = " ```rust,ignore")]
1655 #![cfg_attr(not(target_os = "redox"), doc = " ```rust")]
1656     //! use std::time::{Duration, Instant};
1657     //!
1658     //! use nix::unistd::{alarm, pause};
1659     //! use nix::sys::signal::*;
1660     //!
1661     //! // We need to setup an empty signal handler to catch the alarm signal,
1662     //! // otherwise the program will be terminated once the signal is delivered.
1663     //! extern fn signal_handler(_: nix::libc::c_int) { }
1664     //! let sa = SigAction::new(
1665     //!     SigHandler::Handler(signal_handler),
1666     //!     SaFlags::SA_RESTART,
1667     //!     SigSet::empty()
1668     //! );
1669     //! unsafe {
1670     //!     sigaction(Signal::SIGALRM, &sa);
1671     //! }
1672     //!
1673     //! let start = Instant::now();
1674     //!
1675     //! // Set an alarm for 1 second from now.
1676     //! alarm::set(1);
1677     //!
1678     //! // Pause the process until the alarm signal is received.
1679     //! let mut sigset = SigSet::empty();
1680     //! sigset.add(Signal::SIGALRM);
1681     //! sigset.wait();
1682     //!
1683     //! assert!(start.elapsed() >= Duration::from_secs(1));
1684     //! ```
1685     //!
1686     //! # References
1687     //!
1688     //! See also [alarm(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/alarm.html).
1689 
1690     /// Schedule an alarm signal.
1691     ///
1692     /// This will cause the system to generate a `SIGALRM` signal for the
1693     /// process after the specified number of seconds have elapsed.
1694     ///
1695     /// Returns the leftover time of a previously set alarm if there was one.
set(secs: libc::c_uint) -> Option<libc::c_uint>1696     pub fn set(secs: libc::c_uint) -> Option<libc::c_uint> {
1697         assert!(secs != 0, "passing 0 to `alarm::set` is not allowed, to cancel an alarm use `alarm::cancel`");
1698         alarm(secs)
1699     }
1700 
1701     /// Cancel an previously set alarm signal.
1702     ///
1703     /// Returns the leftover time of a previously set alarm if there was one.
cancel() -> Option<libc::c_uint>1704     pub fn cancel() -> Option<libc::c_uint> {
1705         alarm(0)
1706     }
1707 
alarm(secs: libc::c_uint) -> Option<libc::c_uint>1708     fn alarm(secs: libc::c_uint) -> Option<libc::c_uint> {
1709         match unsafe { libc::alarm(secs) } {
1710             0 => None,
1711             secs => Some(secs),
1712         }
1713     }
1714 }
1715 
1716 /// Suspend execution for an interval of time
1717 ///
1718 /// See also [sleep(2)](https://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html#tag_03_705_05)
1719 // Per POSIX, does not fail
1720 #[inline]
sleep(seconds: c_uint) -> c_uint1721 pub fn sleep(seconds: c_uint) -> c_uint {
1722     unsafe { libc::sleep(seconds) }
1723 }
1724 
1725 #[cfg(not(target_os = "redox"))]
1726 pub mod acct {
1727     use crate::{Result, NixPath};
1728     use crate::errno::Errno;
1729     use std::ptr;
1730 
1731     /// Enable process accounting
1732     ///
1733     /// See also [acct(2)](https://linux.die.net/man/2/acct)
enable<P: ?Sized + NixPath>(filename: &P) -> Result<()>1734     pub fn enable<P: ?Sized + NixPath>(filename: &P) -> Result<()> {
1735         let res = filename.with_nix_path(|cstr| {
1736             unsafe { libc::acct(cstr.as_ptr()) }
1737         })?;
1738 
1739         Errno::result(res).map(drop)
1740     }
1741 
1742     /// Disable process accounting
disable() -> Result<()>1743     pub fn disable() -> Result<()> {
1744         let res = unsafe { libc::acct(ptr::null()) };
1745 
1746         Errno::result(res).map(drop)
1747     }
1748 }
1749 
1750 /// Creates a regular file which persists even after process termination
1751 ///
1752 /// * `template`: a path whose 6 rightmost characters must be X, e.g. `/tmp/tmpfile_XXXXXX`
1753 /// * returns: tuple of file descriptor and filename
1754 ///
1755 /// Err is returned either if no temporary filename could be created or the template doesn't
1756 /// end with XXXXXX
1757 ///
1758 /// See also [mkstemp(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkstemp.html)
1759 ///
1760 /// # Example
1761 ///
1762 /// ```rust
1763 /// use nix::unistd;
1764 ///
1765 /// let _ = match unistd::mkstemp("/tmp/tempfile_XXXXXX") {
1766 ///     Ok((fd, path)) => {
1767 ///         unistd::unlink(path.as_path()).unwrap(); // flag file to be deleted at app termination
1768 ///         fd
1769 ///     }
1770 ///     Err(e) => panic!("mkstemp failed: {}", e)
1771 /// };
1772 /// // do something with fd
1773 /// ```
1774 #[inline]
mkstemp<P: ?Sized + NixPath>(template: &P) -> Result<(RawFd, PathBuf)>1775 pub fn mkstemp<P: ?Sized + NixPath>(template: &P) -> Result<(RawFd, PathBuf)> {
1776     let mut path = template.with_nix_path(|path| {path.to_bytes_with_nul().to_owned()})?;
1777     let p = path.as_mut_ptr() as *mut _;
1778     let fd = unsafe { libc::mkstemp(p) };
1779     let last = path.pop(); // drop the trailing nul
1780     debug_assert!(last == Some(b'\0'));
1781     let pathname = OsString::from_vec(path);
1782     Errno::result(fd)?;
1783     Ok((fd, PathBuf::from(pathname)))
1784 }
1785 
1786 /// Variable names for `pathconf`
1787 ///
1788 /// Nix uses the same naming convention for these variables as the
1789 /// [getconf(1)](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/getconf.html) utility.
1790 /// That is, `PathconfVar` variables have the same name as the abstract
1791 /// variables  shown in the `pathconf(2)` man page.  Usually, it's the same as
1792 /// the C variable name without the leading `_PC_`.
1793 ///
1794 /// POSIX 1003.1-2008 standardizes all of these variables, but some OSes choose
1795 /// not to implement variables that cannot change at runtime.
1796 ///
1797 /// # References
1798 ///
1799 /// - [pathconf(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pathconf.html)
1800 /// - [limits.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html)
1801 /// - [unistd.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/unistd.h.html)
1802 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1803 #[repr(i32)]
1804 pub enum PathconfVar {
1805     #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "linux",
1806               target_os = "netbsd", target_os = "openbsd", target_os = "redox"))]
1807     /// Minimum number of bits needed to represent, as a signed integer value,
1808     /// the maximum size of a regular file allowed in the specified directory.
1809     FILESIZEBITS = libc::_PC_FILESIZEBITS,
1810     /// Maximum number of links to a single file.
1811     LINK_MAX = libc::_PC_LINK_MAX,
1812     /// Maximum number of bytes in a terminal canonical input line.
1813     MAX_CANON = libc::_PC_MAX_CANON,
1814     /// Minimum number of bytes for which space is available in a terminal input
1815     /// queue; therefore, the maximum number of bytes a conforming application
1816     /// may require to be typed as input before reading them.
1817     MAX_INPUT = libc::_PC_MAX_INPUT,
1818     /// Maximum number of bytes in a filename (not including the terminating
1819     /// null of a filename string).
1820     NAME_MAX = libc::_PC_NAME_MAX,
1821     /// Maximum number of bytes the implementation will store as a pathname in a
1822     /// user-supplied buffer of unspecified size, including the terminating null
1823     /// character. Minimum number the implementation will accept as the maximum
1824     /// number of bytes in a pathname.
1825     PATH_MAX = libc::_PC_PATH_MAX,
1826     /// Maximum number of bytes that is guaranteed to be atomic when writing to
1827     /// a pipe.
1828     PIPE_BUF = libc::_PC_PIPE_BUF,
1829     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "illumos",
1830               target_os = "linux", target_os = "netbsd", target_os = "openbsd",
1831               target_os = "redox", target_os = "solaris"))]
1832     /// Symbolic links can be created.
1833     POSIX2_SYMLINKS = libc::_PC_2_SYMLINKS,
1834     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1835               target_os = "linux", target_os = "openbsd", target_os = "redox"))]
1836     /// Minimum number of bytes of storage actually allocated for any portion of
1837     /// a file.
1838     POSIX_ALLOC_SIZE_MIN = libc::_PC_ALLOC_SIZE_MIN,
1839     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1840               target_os = "linux", target_os = "openbsd"))]
1841     /// Recommended increment for file transfer sizes between the
1842     /// `POSIX_REC_MIN_XFER_SIZE` and `POSIX_REC_MAX_XFER_SIZE` values.
1843     POSIX_REC_INCR_XFER_SIZE = libc::_PC_REC_INCR_XFER_SIZE,
1844     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1845               target_os = "linux", target_os = "openbsd", target_os = "redox"))]
1846     /// Maximum recommended file transfer size.
1847     POSIX_REC_MAX_XFER_SIZE = libc::_PC_REC_MAX_XFER_SIZE,
1848     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1849               target_os = "linux", target_os = "openbsd", target_os = "redox"))]
1850     /// Minimum recommended file transfer size.
1851     POSIX_REC_MIN_XFER_SIZE = libc::_PC_REC_MIN_XFER_SIZE,
1852     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1853               target_os = "linux", target_os = "openbsd", target_os = "redox"))]
1854     ///  Recommended file transfer buffer alignment.
1855     POSIX_REC_XFER_ALIGN = libc::_PC_REC_XFER_ALIGN,
1856     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1857               target_os = "illumos", target_os = "linux", target_os = "netbsd",
1858               target_os = "openbsd", target_os = "redox", target_os = "solaris"))]
1859     /// Maximum number of bytes in a symbolic link.
1860     SYMLINK_MAX = libc::_PC_SYMLINK_MAX,
1861     /// The use of `chown` and `fchown` is restricted to a process with
1862     /// appropriate privileges, and to changing the group ID of a file only to
1863     /// the effective group ID of the process or to one of its supplementary
1864     /// group IDs.
1865     _POSIX_CHOWN_RESTRICTED = libc::_PC_CHOWN_RESTRICTED,
1866     /// Pathname components longer than {NAME_MAX} generate an error.
1867     _POSIX_NO_TRUNC = libc::_PC_NO_TRUNC,
1868     /// This symbol shall be defined to be the value of a character that shall
1869     /// disable terminal special character handling.
1870     _POSIX_VDISABLE = libc::_PC_VDISABLE,
1871     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1872               target_os = "illumos", target_os = "linux", target_os = "openbsd",
1873               target_os = "redox", target_os = "solaris"))]
1874     /// Asynchronous input or output operations may be performed for the
1875     /// associated file.
1876     _POSIX_ASYNC_IO = libc::_PC_ASYNC_IO,
1877     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1878               target_os = "illumos", target_os = "linux", target_os = "openbsd",
1879               target_os = "redox", target_os = "solaris"))]
1880     /// Prioritized input or output operations may be performed for the
1881     /// associated file.
1882     _POSIX_PRIO_IO = libc::_PC_PRIO_IO,
1883     #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd",
1884               target_os = "illumos", target_os = "linux", target_os = "netbsd",
1885               target_os = "openbsd", target_os = "redox", target_os = "solaris"))]
1886     /// Synchronized input or output operations may be performed for the
1887     /// associated file.
1888     _POSIX_SYNC_IO = libc::_PC_SYNC_IO,
1889     #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))]
1890     /// The resolution in nanoseconds for all file timestamps.
1891     _POSIX_TIMESTAMP_RESOLUTION = libc::_PC_TIMESTAMP_RESOLUTION
1892 }
1893 
1894 /// Like `pathconf`, but works with file descriptors instead of paths (see
1895 /// [fpathconf(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pathconf.html))
1896 ///
1897 /// # Parameters
1898 ///
1899 /// - `fd`:   The file descriptor whose variable should be interrogated
1900 /// - `var`:  The pathconf variable to lookup
1901 ///
1902 /// # Returns
1903 ///
1904 /// - `Ok(Some(x))`: the variable's limit (for limit variables) or its
1905 ///     implementation level (for option variables).  Implementation levels are
1906 ///     usually a decimal-coded date, such as 200112 for POSIX 2001.12
1907 /// - `Ok(None)`: the variable has no limit (for limit variables) or is
1908 ///     unsupported (for option variables)
1909 /// - `Err(x)`: an error occurred
fpathconf(fd: RawFd, var: PathconfVar) -> Result<Option<c_long>>1910 pub fn fpathconf(fd: RawFd, var: PathconfVar) -> Result<Option<c_long>> {
1911     let raw = unsafe {
1912         Errno::clear();
1913         libc::fpathconf(fd, var as c_int)
1914     };
1915     if raw == -1 {
1916         if errno::errno() == 0 {
1917             Ok(None)
1918         } else {
1919             Err(Error::from(Errno::last()))
1920         }
1921     } else {
1922         Ok(Some(raw))
1923     }
1924 }
1925 
1926 /// Get path-dependent configurable system variables (see
1927 /// [pathconf(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pathconf.html))
1928 ///
1929 /// Returns the value of a path-dependent configurable system variable.  Most
1930 /// supported variables also have associated compile-time constants, but POSIX
1931 /// allows their values to change at runtime.  There are generally two types of
1932 /// `pathconf` variables: options and limits.  See [pathconf(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pathconf.html) for more details.
1933 ///
1934 /// # Parameters
1935 ///
1936 /// - `path`: Lookup the value of `var` for this file or directory
1937 /// - `var`:  The `pathconf` variable to lookup
1938 ///
1939 /// # Returns
1940 ///
1941 /// - `Ok(Some(x))`: the variable's limit (for limit variables) or its
1942 ///     implementation level (for option variables).  Implementation levels are
1943 ///     usually a decimal-coded date, such as 200112 for POSIX 2001.12
1944 /// - `Ok(None)`: the variable has no limit (for limit variables) or is
1945 ///     unsupported (for option variables)
1946 /// - `Err(x)`: an error occurred
pathconf<P: ?Sized + NixPath>(path: &P, var: PathconfVar) -> Result<Option<c_long>>1947 pub fn pathconf<P: ?Sized + NixPath>(path: &P, var: PathconfVar) -> Result<Option<c_long>> {
1948     let raw = path.with_nix_path(|cstr| {
1949         unsafe {
1950             Errno::clear();
1951             libc::pathconf(cstr.as_ptr(), var as c_int)
1952         }
1953     })?;
1954     if raw == -1 {
1955         if errno::errno() == 0 {
1956             Ok(None)
1957         } else {
1958             Err(Error::from(Errno::last()))
1959         }
1960     } else {
1961         Ok(Some(raw))
1962     }
1963 }
1964 
1965 /// Variable names for `sysconf`
1966 ///
1967 /// Nix uses the same naming convention for these variables as the
1968 /// [getconf(1)](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/getconf.html) utility.
1969 /// That is, `SysconfVar` variables have the same name as the abstract variables
1970 /// shown in the `sysconf(3)` man page.  Usually, it's the same as the C
1971 /// variable name without the leading `_SC_`.
1972 ///
1973 /// All of these symbols are standardized by POSIX 1003.1-2008, but haven't been
1974 /// implemented by all platforms.
1975 ///
1976 /// # References
1977 ///
1978 /// - [sysconf(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sysconf.html)
1979 /// - [unistd.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/unistd.h.html)
1980 /// - [limits.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html)
1981 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1982 #[repr(i32)]
1983 pub enum SysconfVar {
1984     /// Maximum number of I/O operations in a single list I/O call supported by
1985     /// the implementation.
1986     #[cfg(not(target_os = "redox"))]
1987     AIO_LISTIO_MAX = libc::_SC_AIO_LISTIO_MAX,
1988     /// Maximum number of outstanding asynchronous I/O operations supported by
1989     /// the implementation.
1990     #[cfg(not(target_os = "redox"))]
1991     AIO_MAX = libc::_SC_AIO_MAX,
1992     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
1993               target_os = "ios", target_os="linux", target_os = "macos",
1994               target_os="openbsd"))]
1995     /// The maximum amount by which a process can decrease its asynchronous I/O
1996     /// priority level from its own scheduling priority.
1997     AIO_PRIO_DELTA_MAX = libc::_SC_AIO_PRIO_DELTA_MAX,
1998     /// Maximum length of argument to the exec functions including environment data.
1999     ARG_MAX = libc::_SC_ARG_MAX,
2000     /// Maximum number of functions that may be registered with `atexit`.
2001     #[cfg(not(target_os = "redox"))]
2002     ATEXIT_MAX = libc::_SC_ATEXIT_MAX,
2003     /// Maximum obase values allowed by the bc utility.
2004     #[cfg(not(target_os = "redox"))]
2005     BC_BASE_MAX = libc::_SC_BC_BASE_MAX,
2006     /// Maximum number of elements permitted in an array by the bc utility.
2007     #[cfg(not(target_os = "redox"))]
2008     BC_DIM_MAX = libc::_SC_BC_DIM_MAX,
2009     /// Maximum scale value allowed by the bc utility.
2010     #[cfg(not(target_os = "redox"))]
2011     BC_SCALE_MAX = libc::_SC_BC_SCALE_MAX,
2012     /// Maximum length of a string constant accepted by the bc utility.
2013     #[cfg(not(target_os = "redox"))]
2014     BC_STRING_MAX = libc::_SC_BC_STRING_MAX,
2015     /// Maximum number of simultaneous processes per real user ID.
2016     CHILD_MAX = libc::_SC_CHILD_MAX,
2017     // The number of clock ticks per second.
2018     CLK_TCK = libc::_SC_CLK_TCK,
2019     /// Maximum number of weights that can be assigned to an entry of the
2020     /// LC_COLLATE order keyword in the locale definition file
2021     #[cfg(not(target_os = "redox"))]
2022     COLL_WEIGHTS_MAX = libc::_SC_COLL_WEIGHTS_MAX,
2023     /// Maximum number of timer expiration overruns.
2024     #[cfg(not(target_os = "redox"))]
2025     DELAYTIMER_MAX = libc::_SC_DELAYTIMER_MAX,
2026     /// Maximum number of expressions that can be nested within parentheses by
2027     /// the expr utility.
2028     #[cfg(not(target_os = "redox"))]
2029     EXPR_NEST_MAX = libc::_SC_EXPR_NEST_MAX,
2030     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2031               target_os = "ios", target_os="linux", target_os = "macos",
2032               target_os="netbsd", target_os="openbsd", target_os = "solaris"))]
2033     /// Maximum length of a host name (not including the terminating null) as
2034     /// returned from the `gethostname` function
2035     HOST_NAME_MAX = libc::_SC_HOST_NAME_MAX,
2036     /// Maximum number of iovec structures that one process has available for
2037     /// use with `readv` or `writev`.
2038     #[cfg(not(target_os = "redox"))]
2039     IOV_MAX = libc::_SC_IOV_MAX,
2040     /// Unless otherwise noted, the maximum length, in bytes, of a utility's
2041     /// input line (either standard input or another file), when the utility is
2042     /// described as processing text files. The length includes room for the
2043     /// trailing <newline>.
2044     #[cfg(not(target_os = "redox"))]
2045     LINE_MAX = libc::_SC_LINE_MAX,
2046     /// Maximum length of a login name.
2047     LOGIN_NAME_MAX = libc::_SC_LOGIN_NAME_MAX,
2048     /// Maximum number of simultaneous supplementary group IDs per process.
2049     NGROUPS_MAX = libc::_SC_NGROUPS_MAX,
2050     /// Initial size of `getgrgid_r` and `getgrnam_r` data buffers
2051     #[cfg(not(target_os = "redox"))]
2052     GETGR_R_SIZE_MAX = libc::_SC_GETGR_R_SIZE_MAX,
2053     /// Initial size of `getpwuid_r` and `getpwnam_r` data buffers
2054     #[cfg(not(target_os = "redox"))]
2055     GETPW_R_SIZE_MAX = libc::_SC_GETPW_R_SIZE_MAX,
2056     /// The maximum number of open message queue descriptors a process may hold.
2057     #[cfg(not(target_os = "redox"))]
2058     MQ_OPEN_MAX = libc::_SC_MQ_OPEN_MAX,
2059     /// The maximum number of message priorities supported by the implementation.
2060     #[cfg(not(target_os = "redox"))]
2061     MQ_PRIO_MAX = libc::_SC_MQ_PRIO_MAX,
2062     /// A value one greater than the maximum value that the system may assign to
2063     /// a newly-created file descriptor.
2064     OPEN_MAX = libc::_SC_OPEN_MAX,
2065     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2066               target_os="linux", target_os = "macos", target_os="openbsd"))]
2067     /// The implementation supports the Advisory Information option.
2068     _POSIX_ADVISORY_INFO = libc::_SC_ADVISORY_INFO,
2069     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2070               target_os = "ios", target_os="linux", target_os = "macos",
2071               target_os="netbsd", target_os="openbsd", target_os = "solaris"))]
2072     /// The implementation supports barriers.
2073     _POSIX_BARRIERS = libc::_SC_BARRIERS,
2074     /// The implementation supports asynchronous input and output.
2075     #[cfg(not(target_os = "redox"))]
2076     _POSIX_ASYNCHRONOUS_IO = libc::_SC_ASYNCHRONOUS_IO,
2077     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2078               target_os = "ios", target_os="linux", target_os = "macos",
2079               target_os="netbsd", target_os="openbsd", target_os = "solaris"))]
2080     /// The implementation supports clock selection.
2081     _POSIX_CLOCK_SELECTION = libc::_SC_CLOCK_SELECTION,
2082     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2083               target_os = "ios", target_os="linux", target_os = "macos",
2084               target_os="netbsd", target_os="openbsd", target_os = "solaris"))]
2085     /// The implementation supports the Process CPU-Time Clocks option.
2086     _POSIX_CPUTIME = libc::_SC_CPUTIME,
2087     /// The implementation supports the File Synchronization option.
2088     #[cfg(not(target_os = "redox"))]
2089     _POSIX_FSYNC = libc::_SC_FSYNC,
2090     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2091               target_os = "ios", target_os="linux", target_os = "macos",
2092               target_os="openbsd", target_os = "solaris"))]
2093     /// The implementation supports the IPv6 option.
2094     _POSIX_IPV6 = libc::_SC_IPV6,
2095     /// The implementation supports job control.
2096     #[cfg(not(target_os = "redox"))]
2097     _POSIX_JOB_CONTROL = libc::_SC_JOB_CONTROL,
2098     /// The implementation supports memory mapped Files.
2099     #[cfg(not(target_os = "redox"))]
2100     _POSIX_MAPPED_FILES = libc::_SC_MAPPED_FILES,
2101     /// The implementation supports the Process Memory Locking option.
2102     #[cfg(not(target_os = "redox"))]
2103     _POSIX_MEMLOCK = libc::_SC_MEMLOCK,
2104     /// The implementation supports the Range Memory Locking option.
2105     #[cfg(not(target_os = "redox"))]
2106     _POSIX_MEMLOCK_RANGE = libc::_SC_MEMLOCK_RANGE,
2107     /// The implementation supports memory protection.
2108     #[cfg(not(target_os = "redox"))]
2109     _POSIX_MEMORY_PROTECTION = libc::_SC_MEMORY_PROTECTION,
2110     /// The implementation supports the Message Passing option.
2111     #[cfg(not(target_os = "redox"))]
2112     _POSIX_MESSAGE_PASSING = libc::_SC_MESSAGE_PASSING,
2113     /// The implementation supports the Monotonic Clock option.
2114     #[cfg(not(target_os = "redox"))]
2115     _POSIX_MONOTONIC_CLOCK = libc::_SC_MONOTONIC_CLOCK,
2116     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2117               target_os = "illumos", target_os = "ios", target_os="linux",
2118               target_os = "macos", target_os="openbsd", target_os = "solaris"))]
2119     /// The implementation supports the Prioritized Input and Output option.
2120     _POSIX_PRIORITIZED_IO = libc::_SC_PRIORITIZED_IO,
2121     /// The implementation supports the Process Scheduling option.
2122     #[cfg(not(target_os = "redox"))]
2123     _POSIX_PRIORITY_SCHEDULING = libc::_SC_PRIORITY_SCHEDULING,
2124     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2125               target_os = "ios", target_os="linux", target_os = "macos",
2126               target_os="openbsd", target_os = "solaris"))]
2127     /// The implementation supports the Raw Sockets option.
2128     _POSIX_RAW_SOCKETS = libc::_SC_RAW_SOCKETS,
2129     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2130               target_os = "ios", target_os="linux", target_os = "macos",
2131               target_os="netbsd", target_os="openbsd", target_os = "solaris"))]
2132     /// The implementation supports read-write locks.
2133     _POSIX_READER_WRITER_LOCKS = libc::_SC_READER_WRITER_LOCKS,
2134     #[cfg(any(target_os = "android", target_os="dragonfly", target_os="freebsd",
2135               target_os = "ios", target_os="linux", target_os = "macos",
2136               target_os = "openbsd"))]
2137     /// The implementation supports realtime signals.
2138     _POSIX_REALTIME_SIGNALS = libc::_SC_REALTIME_SIGNALS,
2139     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "illumos",
2140               target_os = "ios", target_os="linux", target_os = "macos",
2141               target_os="netbsd", target_os="openbsd", target_os = "solaris"))]
2142     /// The implementation supports the Regular Expression Handling option.
2143     _POSIX_REGEXP = libc::_SC_REGEXP,
2144     /// Each process has a saved set-user-ID and a saved set-group-ID.
2145     #[cfg(not(target_os = "redox"))]
2146     _POSIX_SAVED_IDS = libc::_SC_SAVED_IDS,
2147     /// The implementation supports semaphores.
2148     #[cfg(not(target_os = "redox"))]
2149     _POSIX_SEMAPHORES = libc::_SC_SEMAPHORES,
2150     /// The implementation supports the Shared Memory Objects option.
2151     #[cfg(not(target_os = "redox"))]
2152     _POSIX_SHARED_MEMORY_OBJECTS = libc::_SC_SHARED_MEMORY_OBJECTS,
2153     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2154               target_os="linux", target_os = "macos", target_os="netbsd",
2155               target_os="openbsd"))]
2156     /// The implementation supports the POSIX shell.
2157     _POSIX_SHELL = libc::_SC_SHELL,
2158     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2159               target_os="linux", target_os = "macos", target_os="netbsd",
2160               target_os="openbsd"))]
2161     /// The implementation supports the Spawn option.
2162     _POSIX_SPAWN = libc::_SC_SPAWN,
2163     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2164               target_os="linux", target_os = "macos", target_os="netbsd",
2165               target_os="openbsd"))]
2166     /// The implementation supports spin locks.
2167     _POSIX_SPIN_LOCKS = libc::_SC_SPIN_LOCKS,
2168     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2169               target_os="linux", target_os = "macos", target_os="openbsd"))]
2170     /// The implementation supports the Process Sporadic Server option.
2171     _POSIX_SPORADIC_SERVER = libc::_SC_SPORADIC_SERVER,
2172     #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos",
2173               target_os="openbsd"))]
2174     _POSIX_SS_REPL_MAX = libc::_SC_SS_REPL_MAX,
2175     /// The implementation supports the Synchronized Input and Output option.
2176     #[cfg(not(target_os = "redox"))]
2177     _POSIX_SYNCHRONIZED_IO = libc::_SC_SYNCHRONIZED_IO,
2178     /// The implementation supports the Thread Stack Address Attribute option.
2179     #[cfg(not(target_os = "redox"))]
2180     _POSIX_THREAD_ATTR_STACKADDR = libc::_SC_THREAD_ATTR_STACKADDR,
2181     /// The implementation supports the Thread Stack Size Attribute option.
2182     #[cfg(not(target_os = "redox"))]
2183     _POSIX_THREAD_ATTR_STACKSIZE = libc::_SC_THREAD_ATTR_STACKSIZE,
2184     #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos",
2185               target_os="netbsd", target_os="openbsd"))]
2186     /// The implementation supports the Thread CPU-Time Clocks option.
2187     _POSIX_THREAD_CPUTIME = libc::_SC_THREAD_CPUTIME,
2188     /// The implementation supports the Non-Robust Mutex Priority Inheritance
2189     /// option.
2190     #[cfg(not(target_os = "redox"))]
2191     _POSIX_THREAD_PRIO_INHERIT = libc::_SC_THREAD_PRIO_INHERIT,
2192     /// The implementation supports the Non-Robust Mutex Priority Protection option.
2193     #[cfg(not(target_os = "redox"))]
2194     _POSIX_THREAD_PRIO_PROTECT = libc::_SC_THREAD_PRIO_PROTECT,
2195     /// The implementation supports the Thread Execution Scheduling option.
2196     #[cfg(not(target_os = "redox"))]
2197     _POSIX_THREAD_PRIORITY_SCHEDULING = libc::_SC_THREAD_PRIORITY_SCHEDULING,
2198     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2199               target_os="linux", target_os = "macos", target_os="netbsd",
2200               target_os="openbsd"))]
2201     /// The implementation supports the Thread Process-Shared Synchronization
2202     /// option.
2203     _POSIX_THREAD_PROCESS_SHARED = libc::_SC_THREAD_PROCESS_SHARED,
2204     #[cfg(any(target_os="dragonfly", target_os="linux", target_os="openbsd"))]
2205     /// The implementation supports the Robust Mutex Priority Inheritance option.
2206     _POSIX_THREAD_ROBUST_PRIO_INHERIT = libc::_SC_THREAD_ROBUST_PRIO_INHERIT,
2207     #[cfg(any(target_os="dragonfly", target_os="linux", target_os="openbsd"))]
2208     /// The implementation supports the Robust Mutex Priority Protection option.
2209     _POSIX_THREAD_ROBUST_PRIO_PROTECT = libc::_SC_THREAD_ROBUST_PRIO_PROTECT,
2210     /// The implementation supports thread-safe functions.
2211     #[cfg(not(target_os = "redox"))]
2212     _POSIX_THREAD_SAFE_FUNCTIONS = libc::_SC_THREAD_SAFE_FUNCTIONS,
2213     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2214               target_os="linux", target_os = "macos", target_os="openbsd"))]
2215     /// The implementation supports the Thread Sporadic Server option.
2216     _POSIX_THREAD_SPORADIC_SERVER = libc::_SC_THREAD_SPORADIC_SERVER,
2217     /// The implementation supports threads.
2218     #[cfg(not(target_os = "redox"))]
2219     _POSIX_THREADS = libc::_SC_THREADS,
2220     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2221               target_os="linux", target_os = "macos", target_os="openbsd"))]
2222     /// The implementation supports timeouts.
2223     _POSIX_TIMEOUTS = libc::_SC_TIMEOUTS,
2224     /// The implementation supports timers.
2225     #[cfg(not(target_os = "redox"))]
2226     _POSIX_TIMERS = libc::_SC_TIMERS,
2227     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2228               target_os="linux", target_os = "macos", target_os="openbsd"))]
2229     /// The implementation supports the Trace option.
2230     _POSIX_TRACE = libc::_SC_TRACE,
2231     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2232               target_os="linux", target_os = "macos", target_os="openbsd"))]
2233     /// The implementation supports the Trace Event Filter option.
2234     _POSIX_TRACE_EVENT_FILTER = libc::_SC_TRACE_EVENT_FILTER,
2235     #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos",
2236               target_os="openbsd"))]
2237     _POSIX_TRACE_EVENT_NAME_MAX = libc::_SC_TRACE_EVENT_NAME_MAX,
2238     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2239               target_os="linux", target_os = "macos", target_os="openbsd"))]
2240     /// The implementation supports the Trace Inherit option.
2241     _POSIX_TRACE_INHERIT = libc::_SC_TRACE_INHERIT,
2242     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2243               target_os="linux", target_os = "macos", target_os="openbsd"))]
2244     /// The implementation supports the Trace Log option.
2245     _POSIX_TRACE_LOG = libc::_SC_TRACE_LOG,
2246     #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos",
2247               target_os="openbsd"))]
2248     _POSIX_TRACE_NAME_MAX = libc::_SC_TRACE_NAME_MAX,
2249     #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos",
2250               target_os="openbsd"))]
2251     _POSIX_TRACE_SYS_MAX = libc::_SC_TRACE_SYS_MAX,
2252     #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos",
2253               target_os="openbsd"))]
2254     _POSIX_TRACE_USER_EVENT_MAX = libc::_SC_TRACE_USER_EVENT_MAX,
2255     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2256               target_os="linux", target_os = "macos", target_os="openbsd"))]
2257     /// The implementation supports the Typed Memory Objects option.
2258     _POSIX_TYPED_MEMORY_OBJECTS = libc::_SC_TYPED_MEMORY_OBJECTS,
2259     /// Integer value indicating version of this standard (C-language binding)
2260     /// to which the implementation conforms. For implementations conforming to
2261     /// POSIX.1-2008, the value shall be 200809L.
2262     _POSIX_VERSION = libc::_SC_VERSION,
2263     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2264               target_os="linux", target_os = "macos", target_os="netbsd",
2265               target_os="openbsd"))]
2266     /// The implementation provides a C-language compilation environment with
2267     /// 32-bit `int`, `long`, `pointer`, and `off_t` types.
2268     _POSIX_V6_ILP32_OFF32 = libc::_SC_V6_ILP32_OFF32,
2269     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2270               target_os="linux", target_os = "macos", target_os="netbsd",
2271               target_os="openbsd"))]
2272     /// The implementation provides a C-language compilation environment with
2273     /// 32-bit `int`, `long`, and pointer types and an `off_t` type using at
2274     /// least 64 bits.
2275     _POSIX_V6_ILP32_OFFBIG = libc::_SC_V6_ILP32_OFFBIG,
2276     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2277               target_os="linux", target_os = "macos", target_os="netbsd",
2278               target_os="openbsd"))]
2279     /// The implementation provides a C-language compilation environment with
2280     /// 32-bit `int` and 64-bit `long`, `pointer`, and `off_t` types.
2281     _POSIX_V6_LP64_OFF64 = libc::_SC_V6_LP64_OFF64,
2282     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2283               target_os="linux", target_os = "macos", target_os="netbsd",
2284               target_os="openbsd"))]
2285     /// The implementation provides a C-language compilation environment with an
2286     /// `int` type using at least 32 bits and `long`, pointer, and `off_t` types
2287     /// using at least 64 bits.
2288     _POSIX_V6_LPBIG_OFFBIG = libc::_SC_V6_LPBIG_OFFBIG,
2289     /// The implementation supports the C-Language Binding option.
2290     #[cfg(not(target_os = "redox"))]
2291     _POSIX2_C_BIND = libc::_SC_2_C_BIND,
2292     /// The implementation supports the C-Language Development Utilities option.
2293     #[cfg(not(target_os = "redox"))]
2294     _POSIX2_C_DEV = libc::_SC_2_C_DEV,
2295     /// The implementation supports the Terminal Characteristics option.
2296     #[cfg(not(target_os = "redox"))]
2297     _POSIX2_CHAR_TERM = libc::_SC_2_CHAR_TERM,
2298     /// The implementation supports the FORTRAN Development Utilities option.
2299     #[cfg(not(target_os = "redox"))]
2300     _POSIX2_FORT_DEV = libc::_SC_2_FORT_DEV,
2301     /// The implementation supports the FORTRAN Runtime Utilities option.
2302     #[cfg(not(target_os = "redox"))]
2303     _POSIX2_FORT_RUN = libc::_SC_2_FORT_RUN,
2304     /// The implementation supports the creation of locales by the localedef
2305     /// utility.
2306     #[cfg(not(target_os = "redox"))]
2307     _POSIX2_LOCALEDEF = libc::_SC_2_LOCALEDEF,
2308     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2309               target_os="linux", target_os = "macos", target_os="netbsd",
2310               target_os="openbsd"))]
2311     /// The implementation supports the Batch Environment Services and Utilities
2312     /// option.
2313     _POSIX2_PBS = libc::_SC_2_PBS,
2314     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2315               target_os="linux", target_os = "macos", target_os="netbsd",
2316               target_os="openbsd"))]
2317     /// The implementation supports the Batch Accounting option.
2318     _POSIX2_PBS_ACCOUNTING = libc::_SC_2_PBS_ACCOUNTING,
2319     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2320               target_os="linux", target_os = "macos", target_os="netbsd",
2321               target_os="openbsd"))]
2322     /// The implementation supports the Batch Checkpoint/Restart option.
2323     _POSIX2_PBS_CHECKPOINT = libc::_SC_2_PBS_CHECKPOINT,
2324     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2325               target_os="linux", target_os = "macos", target_os="netbsd",
2326               target_os="openbsd"))]
2327     /// The implementation supports the Locate Batch Job Request option.
2328     _POSIX2_PBS_LOCATE = libc::_SC_2_PBS_LOCATE,
2329     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2330               target_os="linux", target_os = "macos", target_os="netbsd",
2331               target_os="openbsd"))]
2332     /// The implementation supports the Batch Job Message Request option.
2333     _POSIX2_PBS_MESSAGE = libc::_SC_2_PBS_MESSAGE,
2334     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2335               target_os="linux", target_os = "macos", target_os="netbsd",
2336               target_os="openbsd"))]
2337     /// The implementation supports the Track Batch Job Request option.
2338     _POSIX2_PBS_TRACK = libc::_SC_2_PBS_TRACK,
2339     /// The implementation supports the Software Development Utilities option.
2340     #[cfg(not(target_os = "redox"))]
2341     _POSIX2_SW_DEV = libc::_SC_2_SW_DEV,
2342     /// The implementation supports the User Portability Utilities option.
2343     #[cfg(not(target_os = "redox"))]
2344     _POSIX2_UPE = libc::_SC_2_UPE,
2345     /// Integer value indicating version of the Shell and Utilities volume of
2346     /// POSIX.1 to which the implementation conforms.
2347     #[cfg(not(target_os = "redox"))]
2348     _POSIX2_VERSION = libc::_SC_2_VERSION,
2349     /// The size of a system page in bytes.
2350     ///
2351     /// POSIX also defines an alias named `PAGESIZE`, but Rust does not allow two
2352     /// enum constants to have the same value, so nix omits `PAGESIZE`.
2353     PAGE_SIZE = libc::_SC_PAGE_SIZE,
2354     #[cfg(not(target_os = "redox"))]
2355     PTHREAD_DESTRUCTOR_ITERATIONS = libc::_SC_THREAD_DESTRUCTOR_ITERATIONS,
2356     #[cfg(not(target_os = "redox"))]
2357     PTHREAD_KEYS_MAX = libc::_SC_THREAD_KEYS_MAX,
2358     #[cfg(not(target_os = "redox"))]
2359     PTHREAD_STACK_MIN = libc::_SC_THREAD_STACK_MIN,
2360     #[cfg(not(target_os = "redox"))]
2361     PTHREAD_THREADS_MAX = libc::_SC_THREAD_THREADS_MAX,
2362     RE_DUP_MAX = libc::_SC_RE_DUP_MAX,
2363     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2364               target_os = "ios", target_os="linux", target_os = "macos",
2365               target_os="openbsd"))]
2366     RTSIG_MAX = libc::_SC_RTSIG_MAX,
2367     #[cfg(not(target_os = "redox"))]
2368     SEM_NSEMS_MAX = libc::_SC_SEM_NSEMS_MAX,
2369     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2370               target_os = "ios", target_os="linux", target_os = "macos",
2371               target_os="openbsd"))]
2372     SEM_VALUE_MAX = libc::_SC_SEM_VALUE_MAX,
2373     #[cfg(any(target_os = "android", target_os="dragonfly", target_os="freebsd",
2374               target_os = "ios", target_os="linux", target_os = "macos",
2375               target_os = "openbsd"))]
2376     SIGQUEUE_MAX = libc::_SC_SIGQUEUE_MAX,
2377     STREAM_MAX = libc::_SC_STREAM_MAX,
2378     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2379               target_os="linux", target_os = "macos", target_os="netbsd",
2380               target_os="openbsd"))]
2381     SYMLOOP_MAX = libc::_SC_SYMLOOP_MAX,
2382     #[cfg(not(target_os = "redox"))]
2383     TIMER_MAX = libc::_SC_TIMER_MAX,
2384     TTY_NAME_MAX = libc::_SC_TTY_NAME_MAX,
2385     TZNAME_MAX = libc::_SC_TZNAME_MAX,
2386     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2387               target_os = "ios", target_os="linux", target_os = "macos",
2388               target_os="openbsd"))]
2389     /// The implementation supports the X/Open Encryption Option Group.
2390     _XOPEN_CRYPT = libc::_SC_XOPEN_CRYPT,
2391     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2392               target_os = "ios", target_os="linux", target_os = "macos",
2393               target_os="openbsd"))]
2394     /// The implementation supports the Issue 4, Version 2 Enhanced
2395     /// Internationalization Option Group.
2396     _XOPEN_ENH_I18N = libc::_SC_XOPEN_ENH_I18N,
2397     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2398               target_os = "ios", target_os="linux", target_os = "macos",
2399               target_os="openbsd"))]
2400     _XOPEN_LEGACY = libc::_SC_XOPEN_LEGACY,
2401     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2402               target_os = "ios", target_os="linux", target_os = "macos",
2403               target_os="openbsd"))]
2404     /// The implementation supports the X/Open Realtime Option Group.
2405     _XOPEN_REALTIME = libc::_SC_XOPEN_REALTIME,
2406     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2407               target_os = "ios", target_os="linux", target_os = "macos",
2408               target_os="openbsd"))]
2409     /// The implementation supports the X/Open Realtime Threads Option Group.
2410     _XOPEN_REALTIME_THREADS = libc::_SC_XOPEN_REALTIME_THREADS,
2411     /// The implementation supports the Issue 4, Version 2 Shared Memory Option
2412     /// Group.
2413     #[cfg(not(target_os = "redox"))]
2414     _XOPEN_SHM = libc::_SC_XOPEN_SHM,
2415     #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios",
2416               target_os="linux", target_os = "macos", target_os="openbsd"))]
2417     /// The implementation supports the XSI STREAMS Option Group.
2418     _XOPEN_STREAMS = libc::_SC_XOPEN_STREAMS,
2419     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2420               target_os = "ios", target_os="linux", target_os = "macos",
2421               target_os="openbsd"))]
2422     /// The implementation supports the XSI option
2423     _XOPEN_UNIX = libc::_SC_XOPEN_UNIX,
2424     #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd",
2425               target_os = "ios", target_os="linux", target_os = "macos",
2426               target_os="openbsd"))]
2427     /// Integer value indicating version of the X/Open Portability Guide to
2428     /// which the implementation conforms.
2429     _XOPEN_VERSION = libc::_SC_XOPEN_VERSION,
2430 }
2431 
2432 /// Get configurable system variables (see
2433 /// [sysconf(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sysconf.html))
2434 ///
2435 /// Returns the value of a configurable system variable.  Most supported
2436 /// variables also have associated compile-time constants, but POSIX
2437 /// allows their values to change at runtime.  There are generally two types of
2438 /// sysconf variables: options and limits.  See sysconf(3) for more details.
2439 ///
2440 /// # Returns
2441 ///
2442 /// - `Ok(Some(x))`: the variable's limit (for limit variables) or its
2443 ///     implementation level (for option variables).  Implementation levels are
2444 ///     usually a decimal-coded date, such as 200112 for POSIX 2001.12
2445 /// - `Ok(None)`: the variable has no limit (for limit variables) or is
2446 ///     unsupported (for option variables)
2447 /// - `Err(x)`: an error occurred
sysconf(var: SysconfVar) -> Result<Option<c_long>>2448 pub fn sysconf(var: SysconfVar) -> Result<Option<c_long>> {
2449     let raw = unsafe {
2450         Errno::clear();
2451         libc::sysconf(var as c_int)
2452     };
2453     if raw == -1 {
2454         if errno::errno() == 0 {
2455             Ok(None)
2456         } else {
2457             Err(Error::from(Errno::last()))
2458         }
2459     } else {
2460         Ok(Some(raw))
2461     }
2462 }
2463 
2464 #[cfg(any(target_os = "android", target_os = "linux"))]
2465 mod pivot_root {
2466     use crate::{Result, NixPath};
2467     use crate::errno::Errno;
2468 
pivot_root<P1: ?Sized + NixPath, P2: ?Sized + NixPath>( new_root: &P1, put_old: &P2) -> Result<()>2469     pub fn pivot_root<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
2470             new_root: &P1, put_old: &P2) -> Result<()> {
2471         let res = new_root.with_nix_path(|new_root| {
2472             put_old.with_nix_path(|put_old| {
2473                 unsafe {
2474                     libc::syscall(libc::SYS_pivot_root, new_root.as_ptr(), put_old.as_ptr())
2475                 }
2476             })
2477         })??;
2478 
2479         Errno::result(res).map(drop)
2480     }
2481 }
2482 
2483 #[cfg(any(target_os = "android", target_os = "freebsd",
2484           target_os = "linux", target_os = "openbsd"))]
2485 mod setres {
2486     use crate::Result;
2487     use crate::errno::Errno;
2488     use super::{Uid, Gid};
2489 
2490     /// Sets the real, effective, and saved uid.
2491     /// ([see setresuid(2)](https://man7.org/linux/man-pages/man2/setresuid.2.html))
2492     ///
2493     /// * `ruid`: real user id
2494     /// * `euid`: effective user id
2495     /// * `suid`: saved user id
2496     /// * returns: Ok or libc error code.
2497     ///
2498     /// Err is returned if the user doesn't have permission to set this UID.
2499     #[inline]
setresuid(ruid: Uid, euid: Uid, suid: Uid) -> Result<()>2500     pub fn setresuid(ruid: Uid, euid: Uid, suid: Uid) -> Result<()> {
2501         let res = unsafe { libc::setresuid(ruid.into(), euid.into(), suid.into()) };
2502 
2503         Errno::result(res).map(drop)
2504     }
2505 
2506     /// Sets the real, effective, and saved gid.
2507     /// ([see setresuid(2)](https://man7.org/linux/man-pages/man2/setresuid.2.html))
2508     ///
2509     /// * `rgid`: real group id
2510     /// * `egid`: effective group id
2511     /// * `sgid`: saved group id
2512     /// * returns: Ok or libc error code.
2513     ///
2514     /// Err is returned if the user doesn't have permission to set this GID.
2515     #[inline]
setresgid(rgid: Gid, egid: Gid, sgid: Gid) -> Result<()>2516     pub fn setresgid(rgid: Gid, egid: Gid, sgid: Gid) -> Result<()> {
2517         let res = unsafe { libc::setresgid(rgid.into(), egid.into(), sgid.into()) };
2518 
2519         Errno::result(res).map(drop)
2520     }
2521 }
2522 
2523 #[cfg(any(target_os = "android", target_os = "linux"))]
2524 mod getres {
2525     use crate::Result;
2526     use crate::errno::Errno;
2527     use super::{Uid, Gid};
2528 
2529     /// Real, effective and saved user IDs.
2530     #[derive(Debug, Copy, Clone, Eq, PartialEq)]
2531     pub struct ResUid {
2532         pub real: Uid,
2533         pub effective: Uid,
2534         pub saved: Uid
2535     }
2536 
2537     /// Real, effective and saved group IDs.
2538     #[derive(Debug, Copy, Clone, Eq, PartialEq)]
2539     pub struct ResGid {
2540         pub real: Gid,
2541         pub effective: Gid,
2542         pub saved: Gid
2543     }
2544 
2545     /// Gets the real, effective, and saved user IDs.
2546     ///
2547     /// ([see getresuid(2)](http://man7.org/linux/man-pages/man2/getresuid.2.html))
2548     ///
2549     /// #Returns
2550     ///
2551     /// - `Ok((Uid, Uid, Uid))`: tuple of real, effective and saved uids on success.
2552     /// - `Err(x)`: libc error code on failure.
2553     ///
2554     #[inline]
getresuid() -> Result<ResUid>2555     pub fn getresuid() -> Result<ResUid> {
2556         let mut ruid = libc::uid_t::max_value();
2557         let mut euid = libc::uid_t::max_value();
2558         let mut suid = libc::uid_t::max_value();
2559         let res = unsafe { libc::getresuid(&mut ruid, &mut euid, &mut suid) };
2560 
2561         Errno::result(res).map(|_| ResUid{ real: Uid(ruid), effective: Uid(euid), saved: Uid(suid) })
2562     }
2563 
2564     /// Gets the real, effective, and saved group IDs.
2565     ///
2566     /// ([see getresgid(2)](http://man7.org/linux/man-pages/man2/getresgid.2.html))
2567     ///
2568     /// #Returns
2569     ///
2570     /// - `Ok((Gid, Gid, Gid))`: tuple of real, effective and saved gids on success.
2571     /// - `Err(x)`: libc error code on failure.
2572     ///
2573     #[inline]
getresgid() -> Result<ResGid>2574     pub fn getresgid() -> Result<ResGid> {
2575         let mut rgid = libc::gid_t::max_value();
2576         let mut egid = libc::gid_t::max_value();
2577         let mut sgid = libc::gid_t::max_value();
2578         let res = unsafe { libc::getresgid(&mut rgid, &mut egid, &mut sgid) };
2579 
2580         Errno::result(res).map(|_| ResGid { real: Gid(rgid), effective: Gid(egid), saved: Gid(sgid) } )
2581     }
2582 }
2583 
2584 libc_bitflags!{
2585     /// Options for access()
2586     pub struct AccessFlags : c_int {
2587         /// Test for existence of file.
2588         F_OK;
2589         /// Test for read permission.
2590         R_OK;
2591         /// Test for write permission.
2592         W_OK;
2593         /// Test for execute (search) permission.
2594         X_OK;
2595     }
2596 }
2597 
2598 /// Checks the file named by `path` for accessibility according to the flags given by `amode`
2599 /// See [access(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/access.html)
access<P: ?Sized + NixPath>(path: &P, amode: AccessFlags) -> Result<()>2600 pub fn access<P: ?Sized + NixPath>(path: &P, amode: AccessFlags) -> Result<()> {
2601     let res = path.with_nix_path(|cstr| {
2602         unsafe {
2603             libc::access(cstr.as_ptr(), amode.bits)
2604         }
2605     })?;
2606     Errno::result(res).map(drop)
2607 }
2608 
2609 /// Representation of a User, based on `libc::passwd`
2610 ///
2611 /// The reason some fields in this struct are `String` and others are `CString` is because some
2612 /// fields are based on the user's locale, which could be non-UTF8, while other fields are
2613 /// guaranteed to conform to [`NAME_REGEX`](https://serverfault.com/a/73101/407341), which only
2614 /// contains ASCII.
2615 #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd
2616 #[derive(Debug, Clone, PartialEq)]
2617 pub struct User {
2618     /// Username
2619     pub name: String,
2620     /// User password (probably encrypted)
2621     pub passwd: CString,
2622     /// User ID
2623     pub uid: Uid,
2624     /// Group ID
2625     pub gid: Gid,
2626     /// User information
2627     #[cfg(not(target_os = "android"))]
2628     pub gecos: CString,
2629     /// Home directory
2630     pub dir: PathBuf,
2631     /// Path to shell
2632     pub shell: PathBuf,
2633     /// Login class
2634     #[cfg(not(any(target_os = "android",
2635                   target_os = "fuchsia",
2636                   target_os = "illumos",
2637                   target_os = "linux",
2638                   target_os = "solaris")))]
2639     pub class: CString,
2640     /// Last password change
2641     #[cfg(not(any(target_os = "android",
2642                   target_os = "fuchsia",
2643                   target_os = "illumos",
2644                   target_os = "linux",
2645                   target_os = "solaris")))]
2646     pub change: libc::time_t,
2647     /// Expiration time of account
2648     #[cfg(not(any(target_os = "android",
2649                   target_os = "fuchsia",
2650                   target_os = "illumos",
2651                   target_os = "linux",
2652                   target_os = "solaris")))]
2653     pub expire: libc::time_t
2654 }
2655 
2656 #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd
2657 impl From<&libc::passwd> for User {
from(pw: &libc::passwd) -> User2658     fn from(pw: &libc::passwd) -> User {
2659         unsafe {
2660             User {
2661                 name: CStr::from_ptr((*pw).pw_name).to_string_lossy().into_owned(),
2662                 passwd: CString::new(CStr::from_ptr((*pw).pw_passwd).to_bytes()).unwrap(),
2663                 #[cfg(not(target_os = "android"))]
2664                 gecos: CString::new(CStr::from_ptr((*pw).pw_gecos).to_bytes()).unwrap(),
2665                 dir: PathBuf::from(OsStr::from_bytes(CStr::from_ptr((*pw).pw_dir).to_bytes())),
2666                 shell: PathBuf::from(OsStr::from_bytes(CStr::from_ptr((*pw).pw_shell).to_bytes())),
2667                 uid: Uid::from_raw((*pw).pw_uid),
2668                 gid: Gid::from_raw((*pw).pw_gid),
2669                 #[cfg(not(any(target_os = "android",
2670                               target_os = "fuchsia",
2671                               target_os = "illumos",
2672                               target_os = "linux",
2673                               target_os = "solaris")))]
2674                 class: CString::new(CStr::from_ptr((*pw).pw_class).to_bytes()).unwrap(),
2675                 #[cfg(not(any(target_os = "android",
2676                               target_os = "fuchsia",
2677                               target_os = "illumos",
2678                               target_os = "linux",
2679                               target_os = "solaris")))]
2680                 change: (*pw).pw_change,
2681                 #[cfg(not(any(target_os = "android",
2682                               target_os = "fuchsia",
2683                               target_os = "illumos",
2684                               target_os = "linux",
2685                               target_os = "solaris")))]
2686                 expire: (*pw).pw_expire
2687             }
2688         }
2689     }
2690 }
2691 
2692 #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd
2693 impl User {
from_anything<F>(f: F) -> Result<Option<Self>> where F: Fn(*mut libc::passwd, *mut libc::c_char, libc::size_t, *mut *mut libc::passwd) -> libc::c_int2694     fn from_anything<F>(f: F) -> Result<Option<Self>>
2695     where
2696         F: Fn(*mut libc::passwd,
2697               *mut libc::c_char,
2698               libc::size_t,
2699               *mut *mut libc::passwd) -> libc::c_int
2700     {
2701         let buflimit = 1048576;
2702         let bufsize = match sysconf(SysconfVar::GETPW_R_SIZE_MAX) {
2703             Ok(Some(n)) => n as usize,
2704             Ok(None) | Err(_) => 16384,
2705         };
2706 
2707         let mut cbuf = Vec::with_capacity(bufsize);
2708         let mut pwd = mem::MaybeUninit::<libc::passwd>::uninit();
2709         let mut res = ptr::null_mut();
2710 
2711         loop {
2712             let error = f(pwd.as_mut_ptr(), cbuf.as_mut_ptr(), cbuf.capacity(), &mut res);
2713             if error == 0 {
2714                 if res.is_null() {
2715                     return Ok(None);
2716                 } else {
2717                     let pwd = unsafe { pwd.assume_init() };
2718                     return Ok(Some(User::from(&pwd)));
2719                 }
2720             } else if Errno::last() == Errno::ERANGE {
2721                 // Trigger the internal buffer resizing logic.
2722                 reserve_double_buffer_size(&mut cbuf, buflimit)?;
2723             } else {
2724                 return Err(Error::from(Errno::last()));
2725             }
2726         }
2727     }
2728 
2729     /// Get a user by UID.
2730     ///
2731     /// Internally, this function calls
2732     /// [getpwuid_r(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwuid_r.html)
2733     ///
2734     /// # Examples
2735     ///
2736     /// ```
2737     /// use nix::unistd::{Uid, User};
2738     /// // Returns an Result<Option<User>>, thus the double unwrap.
2739     /// let res = User::from_uid(Uid::from_raw(0)).unwrap().unwrap();
2740     /// assert!(res.name == "root");
2741     /// ```
from_uid(uid: Uid) -> Result<Option<Self>>2742     pub fn from_uid(uid: Uid) -> Result<Option<Self>> {
2743         User::from_anything(|pwd, cbuf, cap, res| {
2744             unsafe { libc::getpwuid_r(uid.0, pwd, cbuf, cap, res) }
2745         })
2746     }
2747 
2748     /// Get a user by name.
2749     ///
2750     /// Internally, this function calls
2751     /// [getpwnam_r(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwuid_r.html)
2752     ///
2753     /// # Examples
2754     ///
2755     /// ```
2756     /// use nix::unistd::User;
2757     /// // Returns an Result<Option<User>>, thus the double unwrap.
2758     /// let res = User::from_name("root").unwrap().unwrap();
2759     /// assert!(res.name == "root");
2760     /// ```
from_name(name: &str) -> Result<Option<Self>>2761     pub fn from_name(name: &str) -> Result<Option<Self>> {
2762         let name = CString::new(name).unwrap();
2763         User::from_anything(|pwd, cbuf, cap, res| {
2764             unsafe { libc::getpwnam_r(name.as_ptr(), pwd, cbuf, cap, res) }
2765         })
2766     }
2767 }
2768 
2769 /// Representation of a Group, based on `libc::group`
2770 #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd
2771 #[derive(Debug, Clone, PartialEq)]
2772 pub struct Group {
2773     /// Group name
2774     pub name: String,
2775     /// Group password
2776     pub passwd: CString,
2777     /// Group ID
2778     pub gid: Gid,
2779     /// List of Group members
2780     pub mem: Vec<String>
2781 }
2782 
2783 #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd
2784 impl From<&libc::group> for Group {
from(gr: &libc::group) -> Group2785     fn from(gr: &libc::group) -> Group {
2786         unsafe {
2787             Group {
2788                 name: CStr::from_ptr((*gr).gr_name).to_string_lossy().into_owned(),
2789                 passwd: CString::new(CStr::from_ptr((*gr).gr_passwd).to_bytes()).unwrap(),
2790                 gid: Gid::from_raw((*gr).gr_gid),
2791                 mem: Group::members((*gr).gr_mem)
2792             }
2793         }
2794     }
2795 }
2796 
2797 #[cfg(not(target_os = "redox"))] // RedoxFS does not support passwd
2798 impl Group {
members(mem: *mut *mut c_char) -> Vec<String>2799     unsafe fn members(mem: *mut *mut c_char) -> Vec<String> {
2800         let mut ret = Vec::new();
2801 
2802         for i in 0.. {
2803             let u = mem.offset(i);
2804             if (*u).is_null() {
2805                 break;
2806             } else {
2807                 let s = CStr::from_ptr(*u).to_string_lossy().into_owned();
2808                 ret.push(s);
2809             }
2810         }
2811 
2812         ret
2813     }
2814 
from_anything<F>(f: F) -> Result<Option<Self>> where F: Fn(*mut libc::group, *mut libc::c_char, libc::size_t, *mut *mut libc::group) -> libc::c_int2815     fn from_anything<F>(f: F) -> Result<Option<Self>>
2816     where
2817         F: Fn(*mut libc::group,
2818               *mut libc::c_char,
2819               libc::size_t,
2820               *mut *mut libc::group) -> libc::c_int
2821     {
2822         let buflimit = 1048576;
2823         let bufsize = match sysconf(SysconfVar::GETGR_R_SIZE_MAX) {
2824             Ok(Some(n)) => n as usize,
2825             Ok(None) | Err(_) => 16384,
2826         };
2827 
2828         let mut cbuf = Vec::with_capacity(bufsize);
2829         let mut grp = mem::MaybeUninit::<libc::group>::uninit();
2830         let mut res = ptr::null_mut();
2831 
2832         loop {
2833             let error = f(grp.as_mut_ptr(), cbuf.as_mut_ptr(), cbuf.capacity(), &mut res);
2834             if error == 0 {
2835                 if res.is_null() {
2836                     return Ok(None);
2837                 } else {
2838                     let grp = unsafe { grp.assume_init() };
2839                     return Ok(Some(Group::from(&grp)));
2840                 }
2841             } else if Errno::last() == Errno::ERANGE {
2842                 // Trigger the internal buffer resizing logic.
2843                 reserve_double_buffer_size(&mut cbuf, buflimit)?;
2844             } else {
2845                 return Err(Error::from(Errno::last()));
2846             }
2847         }
2848     }
2849 
2850     /// Get a group by GID.
2851     ///
2852     /// Internally, this function calls
2853     /// [getgrgid_r(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwuid_r.html)
2854     ///
2855     /// # Examples
2856     ///
2857     // Disable this test on all OS except Linux as root group may not exist.
2858     #[cfg_attr(not(target_os = "linux"), doc = " ```no_run")]
2859     #[cfg_attr(target_os = "linux", doc = " ```")]
2860     /// use nix::unistd::{Gid, Group};
2861     /// // Returns an Result<Option<Group>>, thus the double unwrap.
2862     /// let res = Group::from_gid(Gid::from_raw(0)).unwrap().unwrap();
2863     /// assert!(res.name == "root");
2864     /// ```
from_gid(gid: Gid) -> Result<Option<Self>>2865     pub fn from_gid(gid: Gid) -> Result<Option<Self>> {
2866         Group::from_anything(|grp, cbuf, cap, res| {
2867             unsafe { libc::getgrgid_r(gid.0, grp, cbuf, cap, res) }
2868         })
2869     }
2870 
2871     /// Get a group by name.
2872     ///
2873     /// Internally, this function calls
2874     /// [getgrnam_r(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwuid_r.html)
2875     ///
2876     /// # Examples
2877     ///
2878     // Disable this test on all OS except Linux as root group may not exist.
2879     #[cfg_attr(not(target_os = "linux"), doc = " ```no_run")]
2880     #[cfg_attr(target_os = "linux", doc = " ```")]
2881     /// use nix::unistd::Group;
2882     /// // Returns an Result<Option<Group>>, thus the double unwrap.
2883     /// let res = Group::from_name("root").unwrap().unwrap();
2884     /// assert!(res.name == "root");
2885     /// ```
from_name(name: &str) -> Result<Option<Self>>2886     pub fn from_name(name: &str) -> Result<Option<Self>> {
2887         let name = CString::new(name).unwrap();
2888         Group::from_anything(|grp, cbuf, cap, res| {
2889             unsafe { libc::getgrnam_r(name.as_ptr(), grp, cbuf, cap, res) }
2890         })
2891     }
2892 }
2893 
2894 /// Get the name of the terminal device that is open on file descriptor fd
2895 /// (see [`ttyname(3)`](https://man7.org/linux/man-pages/man3/ttyname.3.html)).
2896 #[cfg(not(target_os = "fuchsia"))]
ttyname(fd: RawFd) -> Result<PathBuf>2897 pub fn ttyname(fd: RawFd) -> Result<PathBuf> {
2898     const PATH_MAX: usize = libc::PATH_MAX as usize;
2899     let mut buf = vec![0_u8; PATH_MAX];
2900     let c_buf = buf.as_mut_ptr() as *mut libc::c_char;
2901 
2902     let ret = unsafe { libc::ttyname_r(fd, c_buf, buf.len()) };
2903     if ret != 0 {
2904         return Err(Error::from(Errno::from_i32(ret)));
2905     }
2906 
2907     let nul = buf.iter().position(|c| *c == b'\0').unwrap();
2908     buf.truncate(nul);
2909     Ok(OsString::from_vec(buf).into())
2910 }
2911 
2912 /// Get the effective user ID and group ID associated with a Unix domain socket.
2913 ///
2914 /// See also [getpeereid(3)](https://www.freebsd.org/cgi/man.cgi?query=getpeereid)
2915 #[cfg(any(
2916     target_os = "macos",
2917     target_os = "ios",
2918     target_os = "freebsd",
2919     target_os = "openbsd",
2920     target_os = "netbsd",
2921     target_os = "dragonfly",
2922 ))]
getpeereid(fd: RawFd) -> Result<(Uid, Gid)>2923 pub fn getpeereid(fd: RawFd) -> Result<(Uid, Gid)> {
2924     let mut uid = 1;
2925     let mut gid = 1;
2926 
2927     let ret = unsafe { libc::getpeereid(fd, &mut uid, &mut gid) };
2928 
2929     Errno::result(ret).map(|_| (Uid(uid), Gid(gid)))
2930 }
2931