1//! Functions which operate on file descriptors.
2
3#[cfg(not(target_os = "wasi"))]
4use crate::fs::Mode;
5#[cfg(not(target_os = "wasi"))]
6use crate::fs::{Gid, Uid};
7use crate::fs::{OFlags, SeekFrom, Timespec};
8use crate::{backend, io};
9use backend::fd::{AsFd, BorrowedFd};
10
11#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
12pub use backend::fs::types::FlockOperation;
13
14#[cfg(not(any(
15 netbsdlike,
16 solarish,
17 target_os = "aix",
18 target_os = "dragonfly",
19 target_os = "espidf",
20 target_os = "nto",
21 target_os = "redox",
22)))]
23pub use backend::fs::types::FallocateFlags;
24
25pub use backend::fs::types::Stat;
26
27#[cfg(not(any(
28 solarish,
29 target_os = "espidf",
30 target_os = "haiku",
31 target_os = "netbsd",
32 target_os = "nto",
33 target_os = "redox",
34 target_os = "wasi",
35)))]
36pub use backend::fs::types::StatFs;
37
38#[cfg(not(any(target_os = "haiku", target_os = "redox", target_os = "wasi")))]
39pub use backend::fs::types::{StatVfs, StatVfsMountFlags};
40
41#[cfg(linux_kernel)]
42pub use backend::fs::types::FsWord;
43
44/// Timestamps used by [`utimensat`] and [`futimens`].
45///
46/// [`utimensat`]: crate::fs::utimensat
47/// [`futimens`]: crate::fs::futimens
48// This is `repr(C)` and specifically laid out to match the representation used
49// by `utimensat` and `futimens`, which expect 2-element arrays of timestamps.
50#[repr(C)]
51#[derive(Clone, Debug)]
52pub struct Timestamps {
53 /// The timestamp of the last access to a filesystem object.
54 pub last_access: Timespec,
55
56 /// The timestamp of the last modification of a filesystem object.
57 pub last_modification: Timespec,
58}
59
60/// The filesystem magic number for procfs.
61///
62/// See [the `fstatfs` manual page] for more information.
63///
64/// [the `fstatfs` manual page]: https://man7.org/linux/man-pages/man2/fstatfs.2.html#DESCRIPTION
65#[cfg(linux_kernel)]
66pub const PROC_SUPER_MAGIC: FsWord = backend::c::PROC_SUPER_MAGIC as FsWord;
67
68/// The filesystem magic number for NFS.
69///
70/// See [the `fstatfs` manual page] for more information.
71///
72/// [the `fstatfs` manual page]: https://man7.org/linux/man-pages/man2/fstatfs.2.html#DESCRIPTION
73#[cfg(linux_kernel)]
74pub const NFS_SUPER_MAGIC: FsWord = backend::c::NFS_SUPER_MAGIC as FsWord;
75
76/// `lseek(fd, offset, whence)`—Repositions a file descriptor within a file.
77///
78/// # References
79/// - [POSIX]
80/// - [Linux]
81///
82/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lseek.html
83/// [Linux]: https://man7.org/linux/man-pages/man2/lseek.2.html
84#[inline]
85#[doc(alias = "lseek")]
86pub fn seek<Fd: AsFd>(fd: Fd, pos: SeekFrom) -> io::Result<u64> {
87 backend::fs::syscalls::seek(fd.as_fd(), pos)
88}
89
90/// `lseek(fd, 0, SEEK_CUR)`—Returns the current position within a file.
91///
92/// Return the current position of the file descriptor. This is a subset of
93/// the functionality of `seek`, but this interface makes it easier for users
94/// to declare their intent not to mutate any state.
95///
96/// # References
97/// - [POSIX]
98/// - [Linux]
99///
100/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lseek.html
101/// [Linux]: https://man7.org/linux/man-pages/man2/lseek.2.html
102#[inline]
103#[doc(alias = "lseek")]
104pub fn tell<Fd: AsFd>(fd: Fd) -> io::Result<u64> {
105 backend::fs::syscalls::tell(fd.as_fd())
106}
107
108/// `fchmod(fd, mode)`—Sets open file or directory permissions.
109///
110/// This implementation does not support [`OFlags::PATH`] file descriptors,
111/// even on platforms where the host libc emulates it.
112///
113/// # References
114/// - [POSIX]
115/// - [Linux]
116///
117/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchmod.html
118/// [Linux]: https://man7.org/linux/man-pages/man2/fchmod.2.html
119#[cfg(not(target_os = "wasi"))]
120#[inline]
121pub fn fchmod<Fd: AsFd>(fd: Fd, mode: Mode) -> io::Result<()> {
122 backend::fs::syscalls::fchmod(fd.as_fd(), mode)
123}
124
125/// `fchown(fd, owner, group)`—Sets open file or directory ownership.
126///
127/// # References
128/// - [POSIX]
129/// - [Linux]
130///
131/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchown.html
132/// [Linux]: https://man7.org/linux/man-pages/man2/fchown.2.html
133#[cfg(not(target_os = "wasi"))]
134#[inline]
135pub fn fchown<Fd: AsFd>(fd: Fd, owner: Option<Uid>, group: Option<Gid>) -> io::Result<()> {
136 backend::fs::syscalls::fchown(fd.as_fd(), owner, group)
137}
138
139/// `fstat(fd)`—Queries metadata for an open file or directory.
140///
141/// [`Mode::from_raw_mode`] and [`FileType::from_raw_mode`] may be used to
142/// interpret the `st_mode` field.
143///
144/// # References
145/// - [POSIX]
146/// - [Linux]
147///
148/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstat.html
149/// [Linux]: https://man7.org/linux/man-pages/man2/fstat.2.html
150/// [`Mode::from_raw_mode`]: Mode::from_raw_mode
151/// [`FileType::from_raw_mode`]: crate::fs::FileType::from_raw_mode
152#[inline]
153pub fn fstat<Fd: AsFd>(fd: Fd) -> io::Result<Stat> {
154 backend::fs::syscalls::fstat(fd.as_fd())
155}
156
157/// `fstatfs(fd)`—Queries filesystem statistics for an open file or directory.
158///
159/// Compared to [`fstatvfs`], this function often provides more information,
160/// though it's less portable.
161///
162/// # References
163/// - [Linux]
164///
165/// [Linux]: https://man7.org/linux/man-pages/man2/fstatfs.2.html
166#[cfg(not(any(
167 solarish,
168 target_os = "espidf",
169 target_os = "haiku",
170 target_os = "netbsd",
171 target_os = "nto",
172 target_os = "redox",
173 target_os = "wasi",
174)))]
175#[inline]
176pub fn fstatfs<Fd: AsFd>(fd: Fd) -> io::Result<StatFs> {
177 backend::fs::syscalls::fstatfs(fd.as_fd())
178}
179
180/// `fstatvfs(fd)`—Queries filesystem statistics for an open file or
181/// directory, POSIX version.
182///
183/// Compared to [`fstatfs`], this function often provides less information,
184/// but it is more portable. But even so, filesystems are very diverse and not
185/// all the fields are meaningful for every filesystem. And `f_fsid` doesn't
186/// seem to have a clear meaning anywhere.
187///
188/// # References
189/// - [POSIX]
190/// - [Linux]
191///
192/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatvfs.html
193/// [Linux]: https://man7.org/linux/man-pages/man2/fstatvfs.2.html
194#[cfg(not(any(target_os = "haiku", target_os = "redox", target_os = "wasi")))]
195#[inline]
196pub fn fstatvfs<Fd: AsFd>(fd: Fd) -> io::Result<StatVfs> {
197 backend::fs::syscalls::fstatvfs(fd.as_fd())
198}
199
200/// `futimens(fd, times)`—Sets timestamps for an open file or directory.
201///
202/// # References
203/// - [POSIX]
204/// - [Linux]
205///
206/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/futimens.html
207/// [Linux]: https://man7.org/linux/man-pages/man2/utimensat.2.html
208#[cfg(not(target_os = "espidf"))]
209#[inline]
210pub fn futimens<Fd: AsFd>(fd: Fd, times: &Timestamps) -> io::Result<()> {
211 backend::fs::syscalls::futimens(fd.as_fd(), times)
212}
213
214/// `fallocate(fd, mode, offset, len)`—Adjusts file allocation.
215///
216/// This is a more general form of `posix_fallocate`, adding a `mode` argument
217/// which modifies the behavior. On platforms which only support
218/// `posix_fallocate` and not the more general form, no `FallocateFlags` values
219/// are defined so it will always be empty.
220///
221/// # References
222/// - [POSIX]
223/// - [Linux `fallocate`]
224/// - [Linux `posix_fallocate`]
225///
226/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_fallocate.html
227/// [Linux `fallocate`]: https://man7.org/linux/man-pages/man2/fallocate.2.html
228/// [Linux `posix_fallocate`]: https://man7.org/linux/man-pages/man3/posix_fallocate.3.html
229#[cfg(not(any(
230 netbsdlike,
231 solarish,
232 target_os = "aix",
233 target_os = "dragonfly",
234 target_os = "espidf",
235 target_os = "nto",
236 target_os = "redox",
237)))] // not implemented in libc for netbsd yet
238#[inline]
239#[doc(alias = "posix_fallocate")]
240pub fn fallocate<Fd: AsFd>(fd: Fd, mode: FallocateFlags, offset: u64, len: u64) -> io::Result<()> {
241 backend::fs::syscalls::fallocate(fd.as_fd(), mode, offset, len)
242}
243
244/// `fcntl(fd, F_GETFL) & O_ACCMODE`
245///
246/// Returns a pair of booleans indicating whether the file descriptor is
247/// readable and/or writable, respectively. This is only reliable on files; for
248/// example, it doesn't reflect whether sockets have been shut down; for
249/// general I/O handle support, use [`io::is_read_write`].
250#[inline]
251pub fn is_file_read_write<Fd: AsFd>(fd: Fd) -> io::Result<(bool, bool)> {
252 _is_file_read_write(fd.as_fd())
253}
254
255pub(crate) fn _is_file_read_write(fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
256 let mode: OFlags = backend::fs::syscalls::fcntl_getfl(fd)?;
257
258 // Check for `O_PATH`.
259 #[cfg(any(linux_kernel, target_os = "emscripten", target_os = "fuchsia"))]
260 if mode.contains(OFlags::PATH) {
261 return Ok((false, false));
262 }
263
264 // Use `RWMODE` rather than `ACCMODE` as `ACCMODE` may include `O_PATH`.
265 // We handled `O_PATH` above.
266 match mode & OFlags::RWMODE {
267 OFlags::RDONLY => Ok((true, false)),
268 OFlags::RDWR => Ok((true, true)),
269 OFlags::WRONLY => Ok((false, true)),
270 _ => unreachable!(),
271 }
272}
273
274/// `fsync(fd)`—Ensures that file data and metadata is written to the
275/// underlying storage device.
276///
277/// On iOS and macOS this isn't sufficient to ensure that data has reached
278/// persistent storage; use [`fcntl_fullfsync`] to ensure that.
279///
280/// # References
281/// - [POSIX]
282/// - [Linux]
283///
284/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fsync.html
285/// [Linux]: https://man7.org/linux/man-pages/man2/fsync.2.html
286/// [`fcntl_fullfsync`]: https://docs.rs/rustix/*/x86_64-apple-darwin/rustix/fs/fn.fcntl_fullfsync.html
287#[inline]
288pub fn fsync<Fd: AsFd>(fd: Fd) -> io::Result<()> {
289 backend::fs::syscalls::fsync(fd.as_fd())
290}
291
292/// `fdatasync(fd)`—Ensures that file data is written to the underlying
293/// storage device.
294///
295/// # References
296/// - [POSIX]
297/// - [Linux]
298///
299/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html
300/// [Linux]: https://man7.org/linux/man-pages/man2/fdatasync.2.html
301#[cfg(not(any(
302 apple,
303 target_os = "dragonfly",
304 target_os = "espidf",
305 target_os = "haiku",
306 target_os = "redox",
307)))]
308#[inline]
309pub fn fdatasync<Fd: AsFd>(fd: Fd) -> io::Result<()> {
310 backend::fs::syscalls::fdatasync(fd.as_fd())
311}
312
313/// `ftruncate(fd, length)`—Sets the length of a file.
314///
315/// # References
316/// - [POSIX]
317/// - [Linux]
318///
319/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
320/// [Linux]: https://man7.org/linux/man-pages/man2/ftruncate.2.html
321#[inline]
322pub fn ftruncate<Fd: AsFd>(fd: Fd, length: u64) -> io::Result<()> {
323 backend::fs::syscalls::ftruncate(fd.as_fd(), length)
324}
325
326/// `flock(fd, operation)`—Acquire or release an advisory lock on an open file.
327///
328/// # References
329/// - [Linux]
330///
331/// [Linux]: https://man7.org/linux/man-pages/man2/flock.2.html
332#[cfg(not(any(target_os = "espidf", target_os = "solaris", target_os = "wasi")))]
333#[inline]
334pub fn flock<Fd: AsFd>(fd: Fd, operation: FlockOperation) -> io::Result<()> {
335 backend::fs::syscalls::flock(fd.as_fd(), operation)
336}
337
338/// `syncfs(fd)`—Flush cached filesystem data.
339///
340/// # References
341/// - [Linux]
342///
343/// [Linux]: https://man7.org/linux/man-pages/man2/syncfs.2.html
344#[cfg(linux_kernel)]
345#[inline]
346pub fn syncfs<Fd: AsFd>(fd: Fd) -> io::Result<()> {
347 backend::fs::syscalls::syncfs(fd.as_fd())
348}
349