-
Notifications
You must be signed in to change notification settings - Fork 677
/
fcntl.rs
1618 lines (1521 loc) · 54.9 KB
/
fcntl.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! File control options
use crate::errno::Errno;
#[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
use core::slice;
use libc::{c_int, c_uint, size_t, ssize_t};
#[cfg(any(
target_os = "netbsd",
apple_targets,
target_os = "dragonfly",
all(target_os = "freebsd", target_arch = "x86_64"),
))]
use std::ffi::CStr;
use std::ffi::OsString;
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
use std::ops::{Deref, DerefMut};
use std::os::unix::ffi::OsStringExt;
#[cfg(not(target_os = "redox"))]
use std::os::unix::io::OwnedFd;
use std::os::unix::io::RawFd;
#[cfg(any(
target_os = "netbsd",
apple_targets,
target_os = "dragonfly",
all(target_os = "freebsd", target_arch = "x86_64"),
))]
use std::path::PathBuf;
#[cfg(any(linux_android, target_os = "freebsd"))]
use std::ptr;
#[cfg(feature = "fs")]
use crate::{sys::stat::Mode, NixPath, Result};
#[cfg(any(
linux_android,
target_os = "emscripten",
target_os = "fuchsia",
target_os = "wasi",
target_env = "uclibc",
target_os = "freebsd"
))]
#[cfg(feature = "fs")]
pub use self::posix_fadvise::{posix_fadvise, PosixFadviseAdvice};
/// A file descriptor referring to the working directory of the current process
/// **that should be ONLY passed to the `dirfd` argument of those `xxat()` functions**.
///
/// # Examples
///
/// Use it in [`openat()`]:
///
/// ```no_run
/// use nix::fcntl::AT_FDCWD;
/// use nix::fcntl::openat;
/// use nix::fcntl::OFlag;
/// use nix::sys::stat::Mode;
///
/// let fd = openat(AT_FDCWD, "foo", OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::empty()).unwrap();
/// ```
///
/// # WARNING
///
/// Do NOT pass this symbol to non-`xxat()` functions, it won't work:
///
/// ```should_panic
/// use nix::errno::Errno;
/// use nix::fcntl::AT_FDCWD;
/// use nix::sys::stat::fstat;
///
/// let never = fstat(AT_FDCWD).unwrap();
/// ```
//
// SAFETY:
// 1. `AT_FDCWD` is usable for the whole process life, so it is `'static`.
// 2. It is not a valid file descriptor, but OS will handle it for us when passed
// to `xxat(2)` calls.
#[cfg(not(target_os = "redox"))] // Redox does not have this
pub const AT_FDCWD: std::os::fd::BorrowedFd<'static> =
unsafe { std::os::fd::BorrowedFd::borrow_raw(libc::AT_FDCWD) };
#[cfg(not(target_os = "redox"))]
#[cfg(any(feature = "fs", feature = "process", feature = "user"))]
libc_bitflags! {
/// Flags that control how the various *at syscalls behave.
#[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "process"))))]
pub struct AtFlags: c_int {
#[allow(missing_docs)]
#[doc(hidden)]
// Should not be used by the public API, but only internally.
AT_REMOVEDIR;
/// Used with [`linkat`](crate::unistd::linkat`) to create a link to a symbolic link's
/// target, instead of to the symbolic link itself.
AT_SYMLINK_FOLLOW;
/// Used with functions like [`fstatat`](crate::sys::stat::fstatat`) to operate on a link
/// itself, instead of the symbolic link's target.
AT_SYMLINK_NOFOLLOW;
/// Don't automount the terminal ("basename") component of pathname if it is a directory
/// that is an automount point.
#[cfg(linux_android)]
AT_NO_AUTOMOUNT;
/// If the provided path is an empty string, operate on the provided directory file
/// descriptor instead.
#[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))]
AT_EMPTY_PATH;
/// Used with [`faccessat`](crate::unistd::faccessat), the checks for accessibility are
/// performed using the effective user and group IDs instead of the real user and group ID
#[cfg(not(target_os = "android"))]
AT_EACCESS;
}
}
#[cfg(any(
feature = "fs",
feature = "term",
all(feature = "fanotify", target_os = "linux")
))]
libc_bitflags!(
/// Configuration options for opened files.
#[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "term", all(feature = "fanotify", target_os = "linux")))))]
pub struct OFlag: c_int {
/// Mask for the access mode of the file.
O_ACCMODE;
/// Use alternate I/O semantics.
#[cfg(target_os = "netbsd")]
O_ALT_IO;
/// Open the file in append-only mode.
O_APPEND;
/// Generate a signal when input or output becomes possible.
#[cfg(not(any(
solarish,
target_os = "aix",
target_os = "haiku"
)))]
O_ASYNC;
/// Closes the file descriptor once an `execve` call is made.
///
/// Also sets the file offset to the beginning of the file.
O_CLOEXEC;
/// Create the file if it does not exist.
O_CREAT;
/// Try to minimize cache effects of the I/O for this file.
#[cfg(any(
freebsdlike,
linux_android,
target_os = "illumos",
target_os = "netbsd"
))]
O_DIRECT;
/// If the specified path isn't a directory, fail.
O_DIRECTORY;
/// Implicitly follow each `write()` with an `fdatasync()`.
#[cfg(any(linux_android, apple_targets, target_os = "freebsd", netbsdlike))]
O_DSYNC;
/// Error out if a file was not created.
O_EXCL;
/// Open for execute only.
#[cfg(target_os = "freebsd")]
O_EXEC;
/// Open with an exclusive file lock.
#[cfg(any(bsd, target_os = "redox"))]
O_EXLOCK;
/// Same as `O_SYNC`.
#[cfg(any(bsd,
all(target_os = "linux", not(target_env = "musl"), not(target_env = "ohos")),
target_os = "redox"))]
O_FSYNC;
/// Allow files whose sizes can't be represented in an `off_t` to be opened.
#[cfg(linux_android)]
O_LARGEFILE;
/// Do not update the file last access time during `read(2)`s.
#[cfg(linux_android)]
O_NOATIME;
/// Don't attach the device as the process' controlling terminal.
#[cfg(not(target_os = "redox"))]
O_NOCTTY;
/// Same as `O_NONBLOCK`.
#[cfg(not(any(target_os = "redox", target_os = "haiku")))]
O_NDELAY;
/// `open()` will fail if the given path is a symbolic link.
O_NOFOLLOW;
/// When possible, open the file in nonblocking mode.
O_NONBLOCK;
/// Don't deliver `SIGPIPE`.
#[cfg(target_os = "netbsd")]
O_NOSIGPIPE;
/// Obtain a file descriptor for low-level access.
///
/// The file itself is not opened and other file operations will fail.
#[cfg(any(linux_android, target_os = "redox", target_os = "freebsd", target_os = "fuchsia"))]
O_PATH;
/// Only allow reading.
///
/// This should not be combined with `O_WRONLY` or `O_RDWR`.
O_RDONLY;
/// Allow both reading and writing.
///
/// This should not be combined with `O_WRONLY` or `O_RDONLY`.
O_RDWR;
/// Similar to `O_DSYNC` but applies to `read`s instead.
#[cfg(any(target_os = "linux", netbsdlike))]
O_RSYNC;
/// Open directory for search only. Skip search permission checks on
/// later `openat()` calls using the obtained file descriptor.
#[cfg(any(
apple_targets,
solarish,
target_os = "netbsd",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "emscripten",
target_os = "aix",
target_os = "wasi"
))]
O_SEARCH;
/// Open with a shared file lock.
#[cfg(any(bsd, target_os = "redox"))]
O_SHLOCK;
/// Implicitly follow each `write()` with an `fsync()`.
#[cfg(not(target_os = "redox"))]
O_SYNC;
/// Create an unnamed temporary file.
#[cfg(linux_android)]
O_TMPFILE;
/// Truncate an existing regular file to 0 length if it allows writing.
O_TRUNC;
/// Restore default TTY attributes.
#[cfg(target_os = "freebsd")]
O_TTY_INIT;
/// Only allow writing.
///
/// This should not be combined with `O_RDONLY` or `O_RDWR`.
O_WRONLY;
}
);
feature! {
#![feature = "fs"]
/// open or create a file for reading, writing or executing
///
/// # See Also
/// [`open`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)
// The conversion is not identical on all operating systems.
#[allow(clippy::useless_conversion)]
pub fn open<P: ?Sized + NixPath>(
path: &P,
oflag: OFlag,
mode: Mode,
) -> Result<std::os::fd::OwnedFd> {
use std::os::fd::FromRawFd;
let fd = path.with_nix_path(|cstr| unsafe {
libc::open(cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint)
})?;
Errno::result(fd)?;
// SAFETY:
//
// `open(2)` should return a valid owned fd on success
Ok( unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) } )
}
/// open or create a file for reading, writing or executing
///
/// The `openat` function is equivalent to the [`open`] function except in the case where the path
/// specifies a relative path. In that case, the file to be opened is determined relative to the
/// directory associated with the file descriptor `dirfd`.
///
/// # See Also
/// [`openat`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/openat.html)
// The conversion is not identical on all operating systems.
#[allow(clippy::useless_conversion)]
#[cfg(not(target_os = "redox"))]
pub fn openat<P: ?Sized + NixPath, Fd: std::os::fd::AsFd>(
dirfd: Fd,
path: &P,
oflag: OFlag,
mode: Mode,
) -> Result<OwnedFd> {
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
let fd = path.with_nix_path(|cstr| unsafe {
libc::openat(dirfd.as_fd().as_raw_fd(), cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint)
})?;
Errno::result(fd)?;
// SAFETY:
//
// `openat(2)` should return a valid owned fd on success
Ok( unsafe { OwnedFd::from_raw_fd(fd) } )
}
cfg_if::cfg_if! {
if #[cfg(target_os = "linux")] {
libc_bitflags! {
/// Path resolution flags.
///
/// See [path resolution(7)](https://man7.org/linux/man-pages/man7/path_resolution.7.html)
/// for details of the resolution process.
pub struct ResolveFlag: libc::c_ulonglong {
/// Do not permit the path resolution to succeed if any component of
/// the resolution is not a descendant of the directory indicated by
/// dirfd. This causes absolute symbolic links (and absolute values of
/// pathname) to be rejected.
RESOLVE_BENEATH;
/// Treat the directory referred to by dirfd as the root directory
/// while resolving pathname.
RESOLVE_IN_ROOT;
/// Disallow all magic-link resolution during path resolution. Magic
/// links are symbolic link-like objects that are most notably found
/// in proc(5); examples include `/proc/[pid]/exe` and `/proc/[pid]/fd/*`.
///
/// See symlink(7) for more details.
RESOLVE_NO_MAGICLINKS;
/// Disallow resolution of symbolic links during path resolution. This
/// option implies RESOLVE_NO_MAGICLINKS.
RESOLVE_NO_SYMLINKS;
/// Disallow traversal of mount points during path resolution (including
/// all bind mounts).
RESOLVE_NO_XDEV;
}
}
/// Specifies how [`openat2()`] should open a pathname.
///
/// # Reference
///
/// * [Linux](https://man7.org/linux/man-pages/man2/open_how.2type.html)
#[repr(transparent)]
#[derive(Clone, Copy, Debug)]
pub struct OpenHow(libc::open_how);
impl OpenHow {
/// Create a new zero-filled `open_how`.
pub fn new() -> Self {
// safety: according to the man page, open_how MUST be zero-initialized
// on init so that unknown fields are also zeroed.
Self(unsafe {
std::mem::MaybeUninit::zeroed().assume_init()
})
}
/// Set the open flags used to open a file, completely overwriting any
/// existing flags.
pub fn flags(mut self, flags: OFlag) -> Self {
let flags = flags.bits() as libc::c_ulonglong;
self.0.flags = flags;
self
}
/// Set the file mode new files will be created with, overwriting any
/// existing flags.
pub fn mode(mut self, mode: Mode) -> Self {
let mode = mode.bits() as libc::c_ulonglong;
self.0.mode = mode;
self
}
/// Set resolve flags, completely overwriting any existing flags.
///
/// See [ResolveFlag] for more detail.
pub fn resolve(mut self, resolve: ResolveFlag) -> Self {
let resolve = resolve.bits();
self.0.resolve = resolve;
self
}
}
// safety: default isn't derivable because libc::open_how must be zeroed
impl Default for OpenHow {
fn default() -> Self {
Self::new()
}
}
/// Open or create a file for reading, writing or executing.
///
/// `openat2` is an extension of the [`openat`] function that allows the caller
/// to control how path resolution happens.
///
/// # See also
///
/// [openat2](https://man7.org/linux/man-pages/man2/openat2.2.html)
pub fn openat2<P: ?Sized + NixPath, Fd: std::os::fd::AsFd>(
dirfd: Fd,
path: &P,
mut how: OpenHow,
) -> Result<OwnedFd> {
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
let fd = path.with_nix_path(|cstr| unsafe {
libc::syscall(
libc::SYS_openat2,
dirfd.as_fd().as_raw_fd(),
cstr.as_ptr(),
&mut how as *mut OpenHow,
std::mem::size_of::<libc::open_how>(),
)
})? as RawFd;
Errno::result(fd)?;
// SAFETY:
//
// `openat2(2)` should return a valid owned fd on success
Ok( unsafe { OwnedFd::from_raw_fd(fd) } )
}
}
}
/// Change the name of a file.
///
/// The `renameat` function is equivalent to `rename` except in the case where either `old_path`
/// or `new_path` specifies a relative path. In such cases, the file to be renamed (or the its new
/// name, respectively) is located relative to `old_dirfd` or `new_dirfd`, respectively
///
/// # See Also
/// [`renameat`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html)
#[cfg(not(target_os = "redox"))]
pub fn renameat<P1: ?Sized + NixPath, P2: ?Sized + NixPath, Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
old_dirfd: Fd1,
old_path: &P1,
new_dirfd: Fd2,
new_path: &P2,
) -> Result<()> {
use std::os::fd::AsRawFd;
let res = old_path.with_nix_path(|old_cstr| {
new_path.with_nix_path(|new_cstr| unsafe {
libc::renameat(
old_dirfd.as_fd().as_raw_fd(),
old_cstr.as_ptr(),
new_dirfd.as_fd().as_raw_fd(),
new_cstr.as_ptr(),
)
})
})??;
Errno::result(res).map(drop)
}
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[cfg(feature = "fs")]
libc_bitflags! {
/// Flags for use with [`renameat2`].
#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
pub struct RenameFlags: u32 {
/// Atomically exchange `old_path` and `new_path`.
RENAME_EXCHANGE;
/// Don't overwrite `new_path` of the rename. Return an error if `new_path` already
/// exists.
RENAME_NOREPLACE;
/// creates a "whiteout" object at the source of the rename at the same time as performing
/// the rename.
///
/// This operation makes sense only for overlay/union filesystem implementations.
RENAME_WHITEOUT;
}
}
feature! {
#![feature = "fs"]
/// Like [`renameat`], but with an additional `flags` argument.
///
/// A `renameat2` call with an empty flags argument is equivalent to `renameat`.
///
/// # See Also
/// * [`rename`](https://man7.org/linux/man-pages/man2/rename.2.html)
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub fn renameat2<P1: ?Sized + NixPath, P2: ?Sized + NixPath, Fd1: std::os::fd::AsFd, Fd2: std::os::fd::AsFd>(
old_dirfd: Fd1,
old_path: &P1,
new_dirfd: Fd2,
new_path: &P2,
flags: RenameFlags,
) -> Result<()> {
use std::os::fd::AsRawFd;
let res = old_path.with_nix_path(|old_cstr| {
new_path.with_nix_path(|new_cstr| unsafe {
libc::renameat2(
old_dirfd.as_fd().as_raw_fd(),
old_cstr.as_ptr(),
new_dirfd.as_fd().as_raw_fd(),
new_cstr.as_ptr(),
flags.bits(),
)
})
})??;
Errno::result(res).map(drop)
}
fn wrap_readlink_result(mut v: Vec<u8>, len: ssize_t) -> Result<OsString> {
unsafe { v.set_len(len as usize) }
v.shrink_to_fit();
Ok(OsString::from_vec(v.to_vec()))
}
/// Read the symlink specified by `path` and `dirfd` and put the contents in `v`.
/// Return the number of bytes placed in `v`.
///
/// This function can call `readlink(2)` or `readlinkat(2)` depending on if `dirfd`
/// is some, if it is, then `readlinkat(2)` is called, otherwise, call `readlink(2)`.
///
/// # Safety
///
/// This function is not I/O-safe considering it employs the `RawFd` type.
unsafe fn readlink_maybe_at<P: ?Sized + NixPath>(
dirfd: Option<RawFd>,
path: &P,
v: &mut Vec<u8>,
) -> Result<libc::ssize_t> {
path.with_nix_path(|cstr| unsafe {
match dirfd {
#[cfg(target_os = "redox")]
Some(_) => unreachable!("redox does not have readlinkat(2)"),
#[cfg(not(target_os = "redox"))]
Some(dirfd) => libc::readlinkat(
dirfd,
cstr.as_ptr(),
v.as_mut_ptr().cast(),
v.capacity() as size_t,
),
None => libc::readlink(
cstr.as_ptr(),
v.as_mut_ptr().cast(),
v.capacity() as size_t,
),
}
})
}
/// The actual implementation of [`readlink(2)`] or [`readlinkat(2)`].
///
/// This function can call `readlink(2)` or `readlinkat(2)` depending on if `dirfd`
/// is some, if it is, then `readlinkat(2)` is called, otherwise, call `readlink(2)`.
///
/// # Safety
///
/// This function is marked unsafe because it uses `RawFd`.
unsafe fn inner_readlink<P: ?Sized + NixPath>(
dirfd: Option<RawFd>,
path: &P,
) -> Result<OsString> {
#[cfg(not(target_os = "hurd"))]
const PATH_MAX: usize = libc::PATH_MAX as usize;
#[cfg(target_os = "hurd")]
const PATH_MAX: usize = 1024; // Hurd does not define a hard limit, so try a guess first
let mut v = Vec::with_capacity(PATH_MAX);
{
// simple case: result is strictly less than `PATH_MAX`
// SAFETY:
//
// If this call of `readlink_maybe_at()` is safe or not depends on the
// usage of `unsafe fn inner_readlink()`.
let res = unsafe { readlink_maybe_at(dirfd, path, &mut v)? };
let len = Errno::result(res)?;
debug_assert!(len >= 0);
if (len as usize) < v.capacity() {
return wrap_readlink_result(v, res);
}
}
// Uh oh, the result is too long...
// Let's try to ask lstat how many bytes to allocate.
let mut try_size = {
let reported_size = match dirfd {
#[cfg(target_os = "redox")]
Some(_) => unreachable!("redox does not have readlinkat(2)"),
#[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))]
Some(dirfd) => {
// SAFETY:
//
// If this call of `borrow_raw()` is safe or not depends on the
// usage of `unsafe fn inner_readlink()`.
let dirfd = unsafe {
std::os::fd::BorrowedFd::borrow_raw(dirfd)
};
let flags = if path.is_empty() {
AtFlags::AT_EMPTY_PATH
} else {
AtFlags::empty()
};
super::sys::stat::fstatat(
dirfd,
path,
flags | AtFlags::AT_SYMLINK_NOFOLLOW,
)
}
#[cfg(not(any(
linux_android,
target_os = "redox",
target_os = "freebsd",
target_os = "hurd"
)))]
Some(dirfd) => {
// SAFETY:
//
// If this call of `borrow_raw()` is safe or not depends on the
// usage of `unsafe fn inner_readlink()`.
let dirfd = unsafe {
std::os::fd::BorrowedFd::borrow_raw(dirfd)
};
super::sys::stat::fstatat(dirfd, path, AtFlags::AT_SYMLINK_NOFOLLOW)
},
None => super::sys::stat::lstat(path),
}
.map(|x| x.st_size)
.unwrap_or(0);
if reported_size > 0 {
// Note: even if `lstat`'s apparently valid answer turns out to be
// wrong, we will still read the full symlink no matter what.
reported_size as usize + 1
} else {
// If lstat doesn't cooperate, or reports an error, be a little less
// precise.
PATH_MAX.max(128) << 1
}
};
loop {
{
v.reserve_exact(try_size);
// SAFETY:
//
// If this call of `readlink_maybe_at()` is safe or not depends on the
// usage of `unsafe fn inner_readlink()`.
let res = unsafe { readlink_maybe_at(dirfd, path, &mut v)? };
let len = Errno::result(res)?;
debug_assert!(len >= 0);
if (len as usize) < v.capacity() {
return wrap_readlink_result(v, res);
}
}
// Ugh! Still not big enough!
match try_size.checked_shl(1) {
Some(next_size) => try_size = next_size,
// It's absurd that this would happen, but handle it sanely
// anyway.
None => break Err(Errno::ENAMETOOLONG),
}
}
}
/// Read value of a symbolic link
///
/// # See Also
/// * [`readlink`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html)
pub fn readlink<P: ?Sized + NixPath>(path: &P) -> Result<OsString> {
// argument `dirfd` should be `None` since we call it from `readlink()`
//
// Do NOT call it with `Some(AT_CWD)` as in that way, we are emulating
// `readlink(2)` with `readlinkat(2)`, which will make us lose `readlink(2)`
// on Redox.
//
// SAFETY:
//
// It is definitely safe because the argument involving `RawFd` is `None`
unsafe { inner_readlink(None, path) }
}
/// Read value of a symbolic link.
///
/// Equivalent to [`readlink` ] except for the case where `path` specifies a
/// relative path, `path` will be interpreted relative to the path specified
/// by `dirfd`. (Use [`AT_FDCWD`] to make it relative to the working directory).
///
/// # See Also
/// * [`readlink`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html)
#[cfg(not(target_os = "redox"))]
pub fn readlinkat<Fd: std::os::fd::AsFd,P: ?Sized + NixPath>(
dirfd: Fd,
path: &P,
) -> Result<OsString> {
use std::os::fd::AsRawFd;
// argument `dirfd` should be `Some` since we call it from `readlinkat()`
//
// SAFETY:
//
// The passed `RawFd` should be valid since it is borrowed from `Fd: AsFd`.
unsafe { inner_readlink(Some(dirfd.as_fd().as_raw_fd()), path) }
}
}
#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "fs")]
libc_bitflags!(
/// Additional flags for file sealing, which allows for limiting operations on a file.
#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
pub struct SealFlag: c_int {
/// Prevents further calls to `fcntl()` with `F_ADD_SEALS`.
F_SEAL_SEAL;
/// The file cannot be reduced in size.
F_SEAL_SHRINK;
/// The size of the file cannot be increased.
F_SEAL_GROW;
/// The file contents cannot be modified.
F_SEAL_WRITE;
/// The file contents cannot be modified, except via shared writable mappings that were
/// created prior to the seal being set. Since Linux 5.1.
#[cfg(linux_android)]
F_SEAL_FUTURE_WRITE;
}
);
#[cfg(feature = "fs")]
libc_bitflags!(
/// Additional configuration flags for `fcntl`'s `F_SETFD`.
#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
pub struct FdFlag: c_int {
/// The file descriptor will automatically be closed during a successful `execve(2)`.
FD_CLOEXEC;
}
);
feature! {
#![feature = "fs"]
/// Commands for use with [`fcntl`].
#[cfg(not(target_os = "redox"))]
#[derive(Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum FcntlArg<'a> {
/// Duplicate the provided file descriptor
F_DUPFD(RawFd),
/// Duplicate the provided file descriptor and set the `FD_CLOEXEC` flag on it.
F_DUPFD_CLOEXEC(RawFd),
/// Get the close-on-exec flag associated with the file descriptor
F_GETFD,
/// Set the close-on-exec flag associated with the file descriptor
F_SETFD(FdFlag), // FD_FLAGS
/// Get descriptor status flags
F_GETFL,
/// Set descriptor status flags
F_SETFL(OFlag), // O_NONBLOCK
/// Set or clear a file segment lock
F_SETLK(&'a libc::flock),
/// Like [`F_SETLK`](FcntlArg::F_SETLK) except that if a shared or exclusive lock is blocked by
/// other locks, the process waits until the request can be satisfied.
F_SETLKW(&'a libc::flock),
/// Get the first lock that blocks the lock description
F_GETLK(&'a mut libc::flock),
/// Acquire or release an open file description lock
#[cfg(linux_android)]
F_OFD_SETLK(&'a libc::flock),
/// Like [`F_OFD_SETLK`](FcntlArg::F_OFD_SETLK) except that if a conflicting lock is held on
/// the file, then wait for that lock to be released.
#[cfg(linux_android)]
F_OFD_SETLKW(&'a libc::flock),
/// Determine whether it would be possible to create the given lock. If not, return details
/// about one existing lock that would prevent it.
#[cfg(linux_android)]
F_OFD_GETLK(&'a mut libc::flock),
/// Add seals to the file
#[cfg(any(
linux_android,
target_os = "freebsd"
))]
F_ADD_SEALS(SealFlag),
/// Get seals associated with the file
#[cfg(any(
linux_android,
target_os = "freebsd"
))]
F_GET_SEALS,
/// Asks the drive to flush all buffered data to permanent storage.
#[cfg(apple_targets)]
F_FULLFSYNC,
/// fsync + issue barrier to drive
#[cfg(apple_targets)]
F_BARRIERFSYNC,
/// Return the capacity of a pipe
#[cfg(linux_android)]
F_GETPIPE_SZ,
/// Change the capacity of a pipe
#[cfg(linux_android)]
F_SETPIPE_SZ(c_int),
/// Look up the path of an open file descriptor, if possible.
#[cfg(any(
target_os = "netbsd",
target_os = "dragonfly",
apple_targets,
))]
F_GETPATH(&'a mut PathBuf),
/// Look up the path of an open file descriptor, if possible.
#[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
F_KINFO(&'a mut PathBuf),
/// Return the full path without firmlinks of the fd.
#[cfg(apple_targets)]
F_GETPATH_NOFIRMLINK(&'a mut PathBuf),
/// Issue an advisory read async with no copy to user
#[cfg(apple_targets)]
F_RDADVISE(libc::radvisory),
/// Turn read ahead off/on
#[cfg(apple_targets)]
F_RDAHEAD(bool),
/// Pre-allocate storage with different policies on fd.
/// Note that we want a mutable reference for the OUT
/// fstore_t field fst_bytesalloc.
#[cfg(apple_targets)]
F_PREALLOCATE(&'a mut libc::fstore_t),
#[cfg(apple_targets)]
/// Get disk device information. In practice,
/// only the file offset data is set.
F_LOG2PHYS(&'a mut libc::off_t),
#[cfg(apple_targets)]
/// Get disk device information. In practice,
/// only the file offset data is set.
/// The difference with F_LOG2PHYS is the struct passed
/// is used as both IN/OUT as both its l2p_devoffset and
/// l2p_contigbytes can be used for more specific queries.
F_LOG2PHYS_EXT(&'a mut libc::log2phys),
/// Transfer any extra space in the file past the logical EOF
/// (as previously allocated via F_PREALLOCATE) to another file.
/// The other file is specified via a file descriptor as the lone extra argument.
/// Both descriptors must reference regular files in the same volume.
#[cfg(apple_targets)]
F_TRANSFEREXTENTS(RawFd),
/// Set or clear the read ahead (pre-fetch) amount for sequential access or
/// disable it with 0 or to system default for any value < 0.
/// It manages how the kernel caches file data.
#[cfg(target_os = "freebsd")]
F_READAHEAD(c_int),
// TODO: Rest of flags
}
/// Commands for use with [`fcntl`].
#[cfg(target_os = "redox")]
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum FcntlArg {
/// Duplicate the provided file descriptor
F_DUPFD(RawFd),
/// Duplicate the provided file descriptor and set the `FD_CLOEXEC` flag on it.
F_DUPFD_CLOEXEC(RawFd),
/// Get the close-on-exec flag associated with the file descriptor
F_GETFD,
/// Set the close-on-exec flag associated with the file descriptor
F_SETFD(FdFlag), // FD_FLAGS
/// Get descriptor status flags
F_GETFL,
/// Set descriptor status flags
F_SETFL(OFlag), // O_NONBLOCK
}
pub use self::FcntlArg::*;
/// Perform various operations on open file descriptors.
///
/// # See Also
/// * [`fcntl`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html)
// TODO: Figure out how to handle value fcntl returns
pub fn fcntl<Fd: std::os::fd::AsFd>(fd: Fd, arg: FcntlArg) -> Result<c_int> {
use std::os::fd::AsRawFd;
let fd = fd.as_fd().as_raw_fd();
let res = unsafe {
match arg {
F_DUPFD(rawfd) => libc::fcntl(fd, libc::F_DUPFD, rawfd),
F_DUPFD_CLOEXEC(rawfd) => {
libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, rawfd)
}
F_GETFD => libc::fcntl(fd, libc::F_GETFD),
F_SETFD(flag) => libc::fcntl(fd, libc::F_SETFD, flag.bits()),
F_GETFL => libc::fcntl(fd, libc::F_GETFL),
F_SETFL(flag) => libc::fcntl(fd, libc::F_SETFL, flag.bits()),
#[cfg(not(target_os = "redox"))]
F_SETLK(flock) => libc::fcntl(fd, libc::F_SETLK, flock),
#[cfg(not(target_os = "redox"))]
F_SETLKW(flock) => libc::fcntl(fd, libc::F_SETLKW, flock),
#[cfg(not(target_os = "redox"))]
F_GETLK(flock) => libc::fcntl(fd, libc::F_GETLK, flock),
#[cfg(linux_android)]
F_OFD_SETLK(flock) => libc::fcntl(fd, libc::F_OFD_SETLK, flock),
#[cfg(linux_android)]
F_OFD_SETLKW(flock) => libc::fcntl(fd, libc::F_OFD_SETLKW, flock),
#[cfg(linux_android)]
F_OFD_GETLK(flock) => libc::fcntl(fd, libc::F_OFD_GETLK, flock),
#[cfg(any(
linux_android,
target_os = "freebsd"
))]
F_ADD_SEALS(flag) => {
libc::fcntl(fd, libc::F_ADD_SEALS, flag.bits())
}
#[cfg(any(
linux_android,
target_os = "freebsd"
))]
F_GET_SEALS => libc::fcntl(fd, libc::F_GET_SEALS),
#[cfg(apple_targets)]
F_FULLFSYNC => libc::fcntl(fd, libc::F_FULLFSYNC),
#[cfg(apple_targets)]
F_BARRIERFSYNC => libc::fcntl(fd, libc::F_BARRIERFSYNC),
#[cfg(linux_android)]
F_GETPIPE_SZ => libc::fcntl(fd, libc::F_GETPIPE_SZ),
#[cfg(linux_android)]
F_SETPIPE_SZ(size) => libc::fcntl(fd, libc::F_SETPIPE_SZ, size),
#[cfg(any(
target_os = "dragonfly",
target_os = "netbsd",
apple_targets,
))]
F_GETPATH(path) => {
let mut buffer = vec![0; libc::PATH_MAX as usize];
let res = libc::fcntl(fd, libc::F_GETPATH, buffer.as_mut_ptr());
let ok_res = Errno::result(res)?;
let optr = CStr::from_bytes_until_nul(&buffer).unwrap();
*path = PathBuf::from(OsString::from(optr.to_str().unwrap()));
return Ok(ok_res)
},
#[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
F_KINFO(path) => {
let mut info: libc::kinfo_file = std::mem::zeroed();
info.kf_structsize = std::mem::size_of::<libc::kinfo_file>() as i32;
let res = libc::fcntl(fd, libc::F_KINFO, &mut info);
let ok_res = Errno::result(res)?;
let p = info.kf_path;
let u8_slice = slice::from_raw_parts(p.as_ptr().cast(), p.len());
let optr = CStr::from_bytes_until_nul(u8_slice).unwrap();
*path = PathBuf::from(OsString::from(optr.to_str().unwrap()));
return Ok(ok_res)
},
#[cfg(apple_targets)]
F_GETPATH_NOFIRMLINK(path) => {
let mut buffer = vec![0; libc::PATH_MAX as usize];
let res = libc::fcntl(fd, libc::F_GETPATH_NOFIRMLINK, buffer.as_mut_ptr());
let ok_res = Errno::result(res)?;
let optr = CStr::from_bytes_until_nul(&buffer).unwrap();
*path = PathBuf::from(OsString::from(optr.to_str().unwrap()));
return Ok(ok_res)
},
#[cfg(apple_targets)]
F_RDADVISE(rad) => {
libc::fcntl(fd, libc::F_RDADVISE, &rad)
},
#[cfg(apple_targets)]
F_LOG2PHYS(offset) => {
let mut info: libc::log2phys = std::mem::zeroed();
let res = libc::fcntl(fd, libc::F_LOG2PHYS, &mut info);
let ok_res = Errno::result(res)?;
*offset = info.l2p_devoffset;
return Ok(ok_res)
}
#[cfg(apple_targets)]
F_LOG2PHYS_EXT(info) => {
libc::fcntl(fd, libc::F_LOG2PHYS_EXT, info)
}
#[cfg(apple_targets)]
F_RDAHEAD(on) => {
let val = if on { 1 } else { 0 };
libc::fcntl(fd, libc::F_RDAHEAD, val)
},
#[cfg(apple_targets)]
F_PREALLOCATE(st) => {
libc::fcntl(fd, libc::F_PREALLOCATE, st)
},
#[cfg(apple_targets)]
F_TRANSFEREXTENTS(rawfd) => {
libc::fcntl(fd, libc::F_TRANSFEREXTENTS, rawfd)
},
#[cfg(target_os = "freebsd")]
F_READAHEAD(val) => {
libc::fcntl(fd, libc::F_READAHEAD, val)
},
}
};
Errno::result(res)
}
/// Operations for use with [`Flock::lock`].
#[cfg(not(any(target_os = "redox", target_os = "solaris")))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum FlockArg {
/// shared file lock
LockShared,
/// exclusive file lock
LockExclusive,
/// Unlock file
Unlock,
/// Shared lock. Do not block when locking.
LockSharedNonblock,
/// Exclusive lock. Do not block when locking.
LockExclusiveNonblock,
#[allow(missing_docs)]
#[deprecated(since = "0.28.0", note = "Use FlockArg::Unlock instead")]
UnlockNonblock,
}
#[allow(missing_docs)]