Debian Codegraph @

third_party/rust/nix/test/test_unistd.rs

raw
1 use libc::{_exit, mode_t, off_t};
2 use nix::errno::Errno;
3 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
4 use nix::fcntl::readlink;
5 use nix::fcntl::OFlag;
6 #[cfg(not(target_os = "redox"))]
7 use nix::fcntl::{self, open};
8 #[cfg(not(any(
9 target_os = "redox",
10 target_os = "fuchsia",
11 target_os = "haiku"
12 )))]
13 use nix::pty::{grantpt, posix_openpt, ptsname, unlockpt};
14 #[cfg(not(target_os = "redox"))]
15 use nix::sys::signal::{
16 sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal,
17 };
18 use nix::sys::stat::{self, Mode, SFlag};
19 use nix::sys::wait::*;
20 use nix::unistd::ForkResult::*;
21 use nix::unistd::*;
22 use std::env;
23 #[cfg(not(any(target_os = "fuchsia", target_os = "redox")))]
24 use std::ffi::CString;
25 #[cfg(not(target_os = "redox"))]
26 use std::fs::DirBuilder;
27 use std::fs::{self, File};
28 use std::io::Write;
29 #[cfg(not(any(
30 target_os = "fuchsia",
31 target_os = "redox",
32 target_os = "haiku"
33 )))]
34 use std::path::Path;
35 use tempfile::{tempdir, tempfile};
36
37 use crate::*;
38
39 #[test]
40 #[cfg(not(any(target_os = "netbsd")))]
41 fn test_fork_and_waitpid() {
42 let _m = crate::FORK_MTX.lock();
43
44 // Safe: Child only calls `_exit`, which is signal-safe
45 match unsafe { fork() }.expect("Error: Fork Failed") {
46 Child => unsafe { _exit(0) },
47 Parent { child } => {
48 // assert that child was created and pid > 0
49 let child_raw: ::libc::pid_t = child.into();
50 assert!(child_raw > 0);
51 let wait_status = waitpid(child, None);
52 match wait_status {
53 // assert that waitpid returned correct status and the pid is the one of the child
54 Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child),
55
56 // panic, must never happen
57 s @ Ok(_) => {
58 panic!("Child exited {s:?}, should never happen")
59 }
60
61 // panic, waitpid should never fail
62 Err(s) => panic!("Error: waitpid returned Err({s:?}"),
63 }
64 }
65 }
66 }
67
68 #[test]
69 #[cfg(target_os = "freebsd")]
70 fn test_rfork_and_waitpid() {
71 let _m = crate::FORK_MTX.lock();
72
73 // Safe: Child only calls `_exit`, which is signal-safe
74 match unsafe { rfork(RforkFlags::RFPROC | RforkFlags::RFTHREAD) }
75 .expect("Error: Rfork Failed")
76 {
77 Child => unsafe { _exit(0) },
78 Parent { child } => {
79 // assert that child was created and pid > 0
80 let child_raw: ::libc::pid_t = child.into();
81 assert!(child_raw > 0);
82 let wait_status = waitpid(child, None);
83 match wait_status {
84 // assert that waitpid returned correct status and the pid is the one of the child
85 Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child),
86
87 // panic, must never happen
88 s @ Ok(_) => {
89 panic!("Child exited {s:?}, should never happen")
90 }
91
92 // panic, waitpid should never fail
93 Err(s) => panic!("Error: waitpid returned Err({s:?}"),
94 }
95 }
96 }
97 }
98
99 #[test]
100 fn test_wait() {
101 // Grab FORK_MTX so wait doesn't reap a different test's child process
102 let _m = crate::FORK_MTX.lock();
103
104 // Safe: Child only calls `_exit`, which is signal-safe
105 match unsafe { fork() }.expect("Error: Fork Failed") {
106 Child => unsafe { _exit(0) },
107 Parent { child } => {
108 let wait_status = wait();
109
110 // just assert that (any) one child returns with WaitStatus::Exited
111 assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0)));
112 }
113 }
114 }
115
116 #[test]
117 fn test_mkstemp() {
118 let mut path = env::temp_dir();
119 path.push("nix_tempfile.XXXXXX");
120
121 let result = mkstemp(&path);
122 match result {
123 Ok((_, path)) => {
124 unlink(path.as_path()).unwrap();
125 }
126 Err(e) => panic!("mkstemp failed: {e}"),
127 }
128 }
129
130 #[test]
131 fn test_mkstemp_directory() {
132 // mkstemp should fail if a directory is given
133 mkstemp(&env::temp_dir()).expect_err("assertion failed");
134 }
135
136 #[test]
137 #[cfg(not(target_os = "redox"))]
138 fn test_mkfifo() {
139 let tempdir = tempdir().unwrap();
140 let mkfifo_fifo = tempdir.path().join("mkfifo_fifo");
141
142 mkfifo(&mkfifo_fifo, Mode::S_IRUSR).unwrap();
143
144 let stats = stat::stat(&mkfifo_fifo).unwrap();
145 let typ = stat::SFlag::from_bits_truncate(stats.st_mode as mode_t);
146 assert_eq!(typ, SFlag::S_IFIFO);
147 }
148
149 #[test]
150 #[cfg(not(target_os = "redox"))]
151 fn test_mkfifo_directory() {
152 // mkfifo should fail if a directory is given
153 mkfifo(&env::temp_dir(), Mode::S_IRUSR).expect_err("assertion failed");
154 }
155
156 #[test]
157 #[cfg(not(any(
158 apple_targets,
159 target_os = "android",
160 target_os = "redox",
161 target_os = "haiku"
162 )))]
163 fn test_mkfifoat_none() {
164 use nix::fcntl::AT_FDCWD;
165
166 let _m = crate::CWD_LOCK.read();
167
168 let tempdir = tempdir().unwrap();
169 let mkfifoat_fifo = tempdir.path().join("mkfifoat_fifo");
170
171 mkfifoat(AT_FDCWD, &mkfifoat_fifo, Mode::S_IRUSR).unwrap();
172
173 let stats = stat::stat(&mkfifoat_fifo).unwrap();
174 let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
175 assert_eq!(typ, SFlag::S_IFIFO);
176 }
177
178 #[test]
179 #[cfg(not(any(
180 apple_targets,
181 target_os = "android",
182 target_os = "redox",
183 target_os = "haiku"
184 )))]
185 fn test_mkfifoat() {
186 use nix::fcntl;
187
188 let tempdir = tempdir().unwrap();
189 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
190 let mkfifoat_name = "mkfifoat_name";
191
192 mkfifoat(&dirfd, mkfifoat_name, Mode::S_IRUSR).unwrap();
193
194 let stats =
195 stat::fstatat(&dirfd, mkfifoat_name, fcntl::AtFlags::empty()).unwrap();
196 let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
197 assert_eq!(typ, SFlag::S_IFIFO);
198 }
199
200 #[test]
201 #[cfg(not(any(
202 apple_targets,
203 target_os = "android",
204 target_os = "redox",
205 target_os = "haiku"
206 )))]
207 fn test_mkfifoat_directory_none() {
208 use nix::fcntl::AT_FDCWD;
209
210 let _m = crate::CWD_LOCK.read();
211
212 // mkfifoat should fail if a directory is given
213 mkfifoat(AT_FDCWD, &env::temp_dir(), Mode::S_IRUSR)
214 .expect_err("assertion failed");
215 }
216
217 #[test]
218 #[cfg(not(any(
219 apple_targets,
220 target_os = "android",
221 target_os = "redox",
222 target_os = "haiku"
223 )))]
224 fn test_mkfifoat_directory() {
225 // mkfifoat should fail if a directory is given
226 let tempdir = tempdir().unwrap();
227 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
228 let mkfifoat_dir = "mkfifoat_dir";
229 stat::mkdirat(&dirfd, mkfifoat_dir, Mode::S_IRUSR).unwrap();
230
231 mkfifoat(&dirfd, mkfifoat_dir, Mode::S_IRUSR)
232 .expect_err("assertion failed");
233 }
234
235 #[test]
236 fn test_getpid() {
237 let pid: ::libc::pid_t = getpid().into();
238 let ppid: ::libc::pid_t = getppid().into();
239 assert!(pid > 0);
240 assert!(ppid > 0);
241 }
242
243 #[test]
244 #[cfg(not(target_os = "redox"))]
245 fn test_getsid() {
246 let none_sid: ::libc::pid_t = getsid(None).unwrap().into();
247 let pid_sid: ::libc::pid_t = getsid(Some(getpid())).unwrap().into();
248 assert!(none_sid > 0);
249 assert_eq!(none_sid, pid_sid);
250 }
251
252 #[cfg(linux_android)]
253 mod linux_android {
254 use nix::unistd::gettid;
255
256 #[test]
257 fn test_gettid() {
258 let tid: ::libc::pid_t = gettid().into();
259 assert!(tid > 0);
260 }
261 }
262
263 #[test]
264 // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
265 #[cfg(not(any(
266 apple_targets,
267 target_os = "redox",
268 target_os = "fuchsia",
269 target_os = "haiku"
270 )))]
271 fn test_setgroups() {
272 // Skip this test when not run as root as `setgroups()` requires root.
273 skip_if_not_root!("test_setgroups");
274
275 let _m = crate::GROUPS_MTX.lock();
276
277 // Save the existing groups
278 let old_groups = getgroups().unwrap();
279
280 // Set some new made up groups
281 let groups = [Gid::from_raw(123), Gid::from_raw(456)];
282 setgroups(&groups).unwrap();
283
284 let new_groups = getgroups().unwrap();
285 assert_eq!(new_groups, groups);
286
287 // Revert back to the old groups
288 setgroups(&old_groups).unwrap();
289 }
290
291 #[test]
292 // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
293 #[cfg(not(any(
294 apple_targets,
295 target_os = "redox",
296 target_os = "fuchsia",
297 target_os = "haiku",
298 solarish
299 )))]
300 fn test_initgroups() {
301 // Skip this test when not run as root as `initgroups()` and `setgroups()`
302 // require root.
303 skip_if_not_root!("test_initgroups");
304
305 let _m = crate::GROUPS_MTX.lock();
306
307 // Save the existing groups
308 let old_groups = getgroups().unwrap();
309
310 // It doesn't matter if the root user is not called "root" or if a user
311 // called "root" doesn't exist. We are just checking that the extra,
312 // made-up group, `123`, is set.
313 // FIXME: Test the other half of initgroups' functionality: whether the
314 // groups that the user belongs to are also set.
315 let user = CString::new("root").unwrap();
316 let group = Gid::from_raw(123);
317 let mut group_list = getgrouplist(&user, group).unwrap();
318 assert!(group_list.contains(&group));
319
320 initgroups(&user, group).unwrap();
321
322 let mut new_groups = getgroups().unwrap();
323
324 new_groups.sort_by_key(|gid| gid.as_raw());
325 group_list.sort_by_key(|gid| gid.as_raw());
326 assert_eq!(new_groups, group_list);
327
328 // Revert back to the old groups
329 setgroups(&old_groups).unwrap();
330 }
331
332 #[cfg(not(any(target_os = "fuchsia", target_os = "redox")))]
333 macro_rules! execve_test_factory (
334 ($test_name:ident, $syscall:ident, $exe: expr $(, $pathname:expr, $flags:expr)*) => (
335
336 #[cfg(test)]
337 mod $test_name {
338 use std::ffi::CStr;
339 use super::*;
340
341 const EMPTY: &'static [u8] = b"\0";
342 const DASH_C: &'static [u8] = b"-c\0";
343 const BIGARG: &'static [u8] = b"echo nix!!! && echo foo=$foo && echo baz=$baz\0";
344 const FOO: &'static [u8] = b"foo=bar\0";
345 const BAZ: &'static [u8] = b"baz=quux\0";
346
347 fn syscall_cstr_ref() -> Result<std::convert::Infallible, nix::Error> {
348 $syscall(
349 $exe,
350 $(CString::new($pathname).unwrap().as_c_str(), )*
351 &[CStr::from_bytes_with_nul(EMPTY).unwrap(),
352 CStr::from_bytes_with_nul(DASH_C).unwrap(),
353 CStr::from_bytes_with_nul(BIGARG).unwrap()],
354 &[CStr::from_bytes_with_nul(FOO).unwrap(),
355 CStr::from_bytes_with_nul(BAZ).unwrap()]
356 $(, $flags)*)
357 }
358
359 fn syscall_cstring() -> Result<std::convert::Infallible, nix::Error> {
360 $syscall(
361 $exe,
362 $(CString::new($pathname).unwrap().as_c_str(), )*
363 &[CString::from(CStr::from_bytes_with_nul(EMPTY).unwrap()),
364 CString::from(CStr::from_bytes_with_nul(DASH_C).unwrap()),
365 CString::from(CStr::from_bytes_with_nul(BIGARG).unwrap())],
366 &[CString::from(CStr::from_bytes_with_nul(FOO).unwrap()),
367 CString::from(CStr::from_bytes_with_nul(BAZ).unwrap())]
368 $(, $flags)*)
369 }
370
371 fn common_test(syscall: fn() -> Result<std::convert::Infallible, nix::Error>) {
372 if "execveat" == stringify!($syscall) {
373 // Though undocumented, Docker's default seccomp profile seems to
374 // block this syscall. https://github.com/nix-rust/nix/issues/1122
375 skip_if_seccomp!($test_name);
376 }
377
378 let m = crate::FORK_MTX.lock();
379 // The `exec`d process will write to `writer`, and we'll read that
380 // data from `reader`.
381 let (reader, writer) = pipe().unwrap();
382
383 // Safe: Child calls `exit`, `dup`, `close` and the provided `exec*` family function.
384 // NOTE: Technically, this makes the macro unsafe to use because you could pass anything.
385 // The tests make sure not to do that, though.
386 match unsafe{fork()}.unwrap() {
387 Child => {
388 // Make `writer` be the stdout of the new process.
389 nix::unistd::dup2_stdout(&writer).unwrap();
390 let r = syscall();
391 let _ = std::io::stderr()
392 .write_all(format!("{:?}", r).as_bytes());
393 // Should only get here in event of error
394 unsafe{ _exit(1) };
395 },
396 Parent { child } => {
397 // Wait for the child to exit.
398 let ws = waitpid(child, None);
399 drop(m);
400 assert_eq!(ws, Ok(WaitStatus::Exited(child, 0)));
401 // Read 1024 bytes.
402 let mut buf = [0u8; 1024];
403 read(&reader, &mut buf).unwrap();
404 // It should contain the things we printed using `/bin/sh`.
405 let string = String::from_utf8_lossy(&buf);
406 assert!(string.contains("nix!!!"));
407 assert!(string.contains("foo=bar"));
408 assert!(string.contains("baz=quux"));
409 }
410 }
411 }
412
413 // These tests frequently fail on musl, probably due to
414 // https://github.com/nix-rust/nix/issues/555
415 #[cfg_attr(target_env = "musl", ignore)]
416 #[test]
417 fn test_cstr_ref() {
418 common_test(syscall_cstr_ref);
419 }
420
421 // These tests frequently fail on musl, probably due to
422 // https://github.com/nix-rust/nix/issues/555
423 #[cfg_attr(target_env = "musl", ignore)]
424 #[test]
425 fn test_cstring() {
426 common_test(syscall_cstring);
427 }
428 }
429
430 )
431 );
432
433 cfg_if! {
434 if #[cfg(target_os = "android")] {
435 execve_test_factory!(test_execve, execve, CString::new("/system/bin/sh").unwrap().as_c_str());
436 execve_test_factory!(test_fexecve, fexecve, &File::open("/system/bin/sh").unwrap());
437 } else if #[cfg(any(freebsdlike, target_os = "linux", target_os = "hurd"))] {
438 // These tests frequently fail on musl, probably due to
439 // https://github.com/nix-rust/nix/issues/555
440 execve_test_factory!(test_execve, execve, CString::new("/bin/sh").unwrap().as_c_str());
441 execve_test_factory!(test_fexecve, fexecve, &File::open("/bin/sh").unwrap());
442 } else if #[cfg(any(solarish, apple_targets, netbsdlike))] {
443 execve_test_factory!(test_execve, execve, CString::new("/bin/sh").unwrap().as_c_str());
444 // No fexecve() on ios, macos, NetBSD, OpenBSD.
445 }
446 }
447
448 #[cfg(any(
449 target_os = "haiku",
450 target_os = "hurd",
451 target_os = "linux",
452 target_os = "openbsd"
453 ))]
454 execve_test_factory!(test_execvpe, execvpe, &CString::new("sh").unwrap());
455
456 cfg_if! {
457 if #[cfg(target_os = "android")] {
458 use nix::fcntl::AtFlags;
459 execve_test_factory!(test_execveat_empty, execveat,
460 &File::open("/system/bin/sh").unwrap(),
461 "", AtFlags::AT_EMPTY_PATH);
462 execve_test_factory!(test_execveat_relative, execveat,
463 &File::open("/system/bin/").unwrap(),
464 "./sh", AtFlags::empty());
465 execve_test_factory!(test_execveat_absolute, execveat,
466 &File::open("/").unwrap(),
467 "/system/bin/sh", AtFlags::empty());
468 } else if #[cfg(all(target_os = "linux", any(target_arch ="x86_64", target_arch ="x86")))] {
469 use nix::fcntl::AtFlags;
470 execve_test_factory!(test_execveat_empty, execveat, &File::open("/bin/sh").unwrap(),
471 "", AtFlags::AT_EMPTY_PATH);
472 execve_test_factory!(test_execveat_relative, execveat, &File::open("/bin/").unwrap(),
473 "./sh", AtFlags::empty());
474 execve_test_factory!(test_execveat_absolute, execveat, &File::open("/").unwrap(),
475 "/bin/sh", AtFlags::empty());
476 }
477 }
478
479 #[test]
480 #[cfg(not(target_os = "fuchsia"))]
481 fn test_fchdir() {
482 // fchdir changes the process's cwd
483 let _dr = crate::DirRestore::new();
484
485 let tmpdir = tempdir().unwrap();
486 let tmpdir_path = tmpdir.path().canonicalize().unwrap();
487 let tmpdir_fd = File::open(&tmpdir_path).unwrap();
488
489 fchdir(&tmpdir_fd).expect("assertion failed");
490 assert_eq!(getcwd().unwrap(), tmpdir_path);
491 }
492
493 #[test]
494 fn test_getcwd() {
495 // chdir changes the process's cwd
496 let _dr = crate::DirRestore::new();
497
498 let tmpdir = tempdir().unwrap();
499 let tmpdir_path = tmpdir.path().canonicalize().unwrap();
500 chdir(&tmpdir_path).expect("assertion failed");
501 assert_eq!(getcwd().unwrap(), tmpdir_path);
502
503 // make path 500 chars longer so that buffer doubling in getcwd
504 // kicks in. Note: One path cannot be longer than 255 bytes
505 // (NAME_MAX) whole path cannot be longer than PATH_MAX (usually
506 // 4096 on linux, 1024 on macos)
507 let mut inner_tmp_dir = tmpdir_path;
508 for _ in 0..5 {
509 let newdir = "a".repeat(100);
510 inner_tmp_dir.push(newdir);
511 mkdir(inner_tmp_dir.as_path(), Mode::S_IRWXU)
512 .expect("assertion failed");
513 }
514 chdir(inner_tmp_dir.as_path()).expect("assertion failed");
515 assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path());
516 }
517
518 #[test]
519 fn test_chown() {
520 // Testing for anything other than our own UID/GID is hard.
521 let uid = Some(getuid());
522 let gid = Some(getgid());
523
524 let tempdir = tempdir().unwrap();
525 let path = tempdir.path().join("file");
526 {
527 File::create(&path).unwrap();
528 }
529
530 chown(&path, uid, gid).unwrap();
531 chown(&path, uid, None).unwrap();
532 chown(&path, None, gid).unwrap();
533
534 fs::remove_file(&path).unwrap();
535 chown(&path, uid, gid).unwrap_err();
536 }
537
538 #[test]
539 fn test_fchown() {
540 // Testing for anything other than our own UID/GID is hard.
541 let uid = Some(getuid());
542 let gid = Some(getgid());
543
544 let file = tempfile().unwrap();
545
546 fchown(&file, uid, gid).unwrap();
547 fchown(&file, uid, None).unwrap();
548 fchown(&file, None, gid).unwrap();
549 }
550
551 #[test]
552 #[cfg(not(target_os = "redox"))]
553 fn test_fchownat() {
554 use nix::fcntl::AtFlags;
555 use nix::fcntl::AT_FDCWD;
556
557 let _dr = crate::DirRestore::new();
558 // Testing for anything other than our own UID/GID is hard.
559 let uid = Some(getuid());
560 let gid = Some(getgid());
561
562 let tempdir = tempdir().unwrap();
563 let path = tempdir.path().join("file");
564 {
565 File::create(&path).unwrap();
566 }
567
568 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
569
570 fchownat(&dirfd, "file", uid, gid, AtFlags::empty()).unwrap();
571
572 chdir(tempdir.path()).unwrap();
573 fchownat(AT_FDCWD, "file", uid, gid, AtFlags::empty()).unwrap();
574
575 fs::remove_file(&path).unwrap();
576 fchownat(AT_FDCWD, "file", uid, gid, AtFlags::empty()).unwrap_err();
577 }
578
579 #[test]
580 fn test_lseek() {
581 const CONTENTS: &[u8] = b"abcdef123456";
582 let mut tmp = tempfile().unwrap();
583 tmp.write_all(CONTENTS).unwrap();
584
585 let offset: off_t = 5;
586 lseek(&tmp, offset, Whence::SeekSet).unwrap();
587
588 let mut buf = [0u8; 7];
589 crate::read_exact(&tmp, &mut buf);
590 assert_eq!(b"f123456", &buf);
591 }
592
593 #[cfg(linux_android)]
594 #[test]
595 fn test_lseek64() {
596 const CONTENTS: &[u8] = b"abcdef123456";
597 let mut tmp = tempfile().unwrap();
598 tmp.write_all(CONTENTS).unwrap();
599
600 lseek64(&tmp, 5, Whence::SeekSet).unwrap();
601
602 let mut buf = [0u8; 7];
603 crate::read_exact(&tmp, &mut buf);
604 assert_eq!(b"f123456", &buf);
605 }
606
607 cfg_if! {
608 if #[cfg(linux_android)] {
609 macro_rules! require_acct{
610 () => {
611 require_capability!("test_acct", CAP_SYS_PACCT);
612 }
613 }
614 } else if #[cfg(target_os = "freebsd")] {
615 macro_rules! require_acct{
616 () => {
617 skip_if_not_root!("test_acct");
618 skip_if_jailed!("test_acct");
619 }
620 }
621 } else if #[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] {
622 macro_rules! require_acct{
623 () => {
624 skip_if_not_root!("test_acct");
625 }
626 }
627 }
628 }
629
630 #[test]
631 #[cfg(not(any(
632 target_os = "redox",
633 target_os = "fuchsia",
634 target_os = "haiku",
635 target_os = "cygwin"
636 )))]
637 fn test_acct() {
638 use std::process::Command;
639 use std::{thread, time};
640 use tempfile::NamedTempFile;
641
642 let _m = crate::FORK_MTX.lock();
643 require_acct!();
644
645 let file = NamedTempFile::new().unwrap();
646 let path = file.path().to_str().unwrap();
647
648 acct::enable(path).unwrap();
649
650 loop {
651 Command::new("echo").arg("Hello world").output().unwrap();
652 let len = fs::metadata(path).unwrap().len();
653 if len > 0 {
654 break;
655 }
656 thread::sleep(time::Duration::from_millis(10));
657 }
658 acct::disable().unwrap();
659 }
660
661 #[cfg_attr(target_os = "hurd", ignore)]
662 #[test]
663 fn test_fpathconf_limited() {
664 let f = tempfile().unwrap();
665 // PATH_MAX is limited on most platforms, so it makes a good test
666 let path_max = fpathconf(f, PathconfVar::PATH_MAX);
667 assert!(
668 path_max
669 .expect("fpathconf failed")
670 .expect("PATH_MAX is unlimited")
671 > 0
672 );
673 }
674
675 #[cfg_attr(target_os = "hurd", ignore)]
676 #[test]
677 fn test_pathconf_limited() {
678 // PATH_MAX is limited on most platforms, so it makes a good test
679 let path_max = pathconf("/", PathconfVar::PATH_MAX);
680 assert!(
681 path_max
682 .expect("pathconf failed")
683 .expect("PATH_MAX is unlimited")
684 > 0
685 );
686 }
687
688 #[cfg_attr(target_os = "hurd", ignore)]
689 #[test]
690 fn test_sysconf_limited() {
691 // OPEN_MAX is limited on most platforms, so it makes a good test
692 let open_max = sysconf(SysconfVar::OPEN_MAX);
693 assert!(
694 open_max
695 .expect("sysconf failed")
696 .expect("OPEN_MAX is unlimited")
697 > 0
698 );
699 }
700
701 #[cfg(target_os = "freebsd")]
702 #[test]
703 fn test_sysconf_unsupported() {
704 // I know of no sysconf variables that are unsupported everywhere, but
705 // _XOPEN_CRYPT is unsupported on FreeBSD 11.0, which is one of the platforms
706 // we test.
707 let open_max = sysconf(SysconfVar::_XOPEN_CRYPT);
708 assert!(open_max.expect("sysconf failed").is_none())
709 }
710
711 #[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))]
712 #[test]
713 fn test_getresuid() {
714 let resuids = getresuid().unwrap();
715 assert_ne!(resuids.real.as_raw(), libc::uid_t::MAX);
716 assert_ne!(resuids.effective.as_raw(), libc::uid_t::MAX);
717 assert_ne!(resuids.saved.as_raw(), libc::uid_t::MAX);
718 }
719
720 #[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))]
721 #[test]
722 fn test_getresgid() {
723 let resgids = getresgid().unwrap();
724 assert_ne!(resgids.real.as_raw(), libc::gid_t::MAX);
725 assert_ne!(resgids.effective.as_raw(), libc::gid_t::MAX);
726 assert_ne!(resgids.saved.as_raw(), libc::gid_t::MAX);
727 }
728
729 // Test that we can create a pair of pipes. No need to verify that they pass
730 // data; that's the domain of the OS, not nix.
731 #[test]
732 fn test_pipe() {
733 let (fd0, fd1) = pipe().unwrap();
734 let m0 = stat::SFlag::from_bits_truncate(
735 stat::fstat(&fd0).unwrap().st_mode as mode_t,
736 );
737 // S_IFIFO means it's a pipe
738 assert_eq!(m0, SFlag::S_IFIFO);
739 let m1 = stat::SFlag::from_bits_truncate(
740 stat::fstat(&fd1).unwrap().st_mode as mode_t,
741 );
742 assert_eq!(m1, SFlag::S_IFIFO);
743 }
744
745 // pipe2(2) is the same as pipe(2), except it allows setting some flags. Check
746 // that we can set a flag.
747 #[cfg(any(
748 linux_android,
749 freebsdlike,
750 solarish,
751 netbsdlike,
752 target_os = "emscripten",
753 target_os = "redox",
754 ))]
755 #[test]
756 fn test_pipe2() {
757 use nix::fcntl::{fcntl, FcntlArg, FdFlag};
758
759 let (fd0, fd1) = pipe2(OFlag::O_CLOEXEC).unwrap();
760 let f0 =
761 FdFlag::from_bits_truncate(fcntl(&fd0, FcntlArg::F_GETFD).unwrap());
762 assert!(f0.contains(FdFlag::FD_CLOEXEC));
763 let f1 =
764 FdFlag::from_bits_truncate(fcntl(&fd1, FcntlArg::F_GETFD).unwrap());
765 assert!(f1.contains(FdFlag::FD_CLOEXEC));
766 }
767
768 #[test]
769 #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))]
770 fn test_truncate() {
771 let tempdir = tempdir().unwrap();
772 let path = tempdir.path().join("file");
773
774 {
775 let mut tmp = File::create(&path).unwrap();
776 const CONTENTS: &[u8] = b"12345678";
777 tmp.write_all(CONTENTS).unwrap();
778 }
779
780 truncate(&path, 4).unwrap();
781
782 let metadata = fs::metadata(&path).unwrap();
783 assert_eq!(4, metadata.len());
784 }
785
786 #[test]
787 fn test_ftruncate() {
788 let tempdir = tempdir().unwrap();
789 let path = tempdir.path().join("file");
790
791 let mut file = File::create(&path).unwrap();
792 const CONTENTS: &[u8] = b"12345678";
793 file.write_all(CONTENTS).unwrap();
794
795 ftruncate(&file, 2).unwrap();
796 drop(file);
797
798 let metadata = fs::metadata(&path).unwrap();
799 assert_eq!(2, metadata.len());
800 }
801
802 // Used in `test_alarm`.
803 #[cfg(not(target_os = "redox"))]
804 static mut ALARM_CALLED: bool = false;
805
806 // Used in `test_alarm`.
807 #[cfg(not(target_os = "redox"))]
808 pub extern "C" fn alarm_signal_handler(raw_signal: libc::c_int) {
809 assert_eq!(raw_signal, libc::SIGALRM, "unexpected signal: {raw_signal}");
810 unsafe { ALARM_CALLED = true };
811 }
812
813 #[test]
814 #[cfg(not(target_os = "redox"))]
815 fn test_alarm() {
816 use std::{
817 thread,
818 time::{Duration, Instant},
819 };
820
821 // Maybe other tests that fork interfere with this one?
822 let _m = crate::SIGNAL_MTX.lock();
823
824 let handler = SigHandler::Handler(alarm_signal_handler);
825 let signal_action =
826 SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty());
827 let old_handler = unsafe {
828 sigaction(Signal::SIGALRM, &signal_action)
829 .expect("unable to set signal handler for alarm")
830 };
831
832 // Set an alarm.
833 assert_eq!(alarm::set(60), None);
834
835 // Overwriting an alarm should return the old alarm.
836 assert_eq!(alarm::set(1), Some(60));
837
838 // We should be woken up after 1 second by the alarm, so we'll sleep for 3
839 // seconds to be sure.
840 let starttime = Instant::now();
841 loop {
842 thread::sleep(Duration::from_millis(100));
843 if unsafe { ALARM_CALLED } {
844 break;
845 }
846 if starttime.elapsed() > Duration::from_secs(3) {
847 panic!("Timeout waiting for SIGALRM");
848 }
849 }
850
851 // Reset the signal.
852 unsafe {
853 sigaction(Signal::SIGALRM, &old_handler)
854 .expect("unable to set signal handler for alarm");
855 }
856 }
857
858 #[test]
859 #[cfg(not(target_os = "redox"))]
860 fn test_canceling_alarm() {
861 let _m = crate::SIGNAL_MTX.lock();
862
863 assert_eq!(alarm::cancel(), None);
864
865 assert_eq!(alarm::set(60), None);
866 assert_eq!(alarm::cancel(), Some(60));
867 }
868
869 #[test]
870 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
871 fn test_symlinkat() {
872 use nix::fcntl::AT_FDCWD;
873
874 let _m = crate::CWD_LOCK.read();
875
876 let tempdir = tempdir().unwrap();
877
878 let target = tempdir.path().join("a");
879 let linkpath = tempdir.path().join("b");
880 symlinkat(&target, AT_FDCWD, &linkpath).unwrap();
881 assert_eq!(
882 readlink(&linkpath).unwrap().to_str().unwrap(),
883 target.to_str().unwrap()
884 );
885
886 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
887 let target = "c";
888 let linkpath = "d";
889 symlinkat(target, &dirfd, linkpath).unwrap();
890 assert_eq!(
891 readlink(&tempdir.path().join(linkpath))
892 .unwrap()
893 .to_str()
894 .unwrap(),
895 target
896 );
897 }
898
899 #[test]
900 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
901 fn test_linkat_file() {
902 use nix::fcntl::AtFlags;
903
904 let tempdir = tempdir().unwrap();
905 let oldfilename = "foo.txt";
906 let oldfilepath = tempdir.path().join(oldfilename);
907
908 let newfilename = "bar.txt";
909 let newfilepath = tempdir.path().join(newfilename);
910
911 // Create file
912 File::create(oldfilepath).unwrap();
913
914 // Get file descriptor for base directory
915 let dirfd =
916 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
917 .unwrap();
918
919 // Attempt hard link file at relative path
920 linkat(
921 &dirfd,
922 oldfilename,
923 &dirfd,
924 newfilename,
925 AtFlags::AT_SYMLINK_FOLLOW,
926 )
927 .unwrap();
928 assert!(newfilepath.exists());
929 }
930
931 #[test]
932 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
933 /// This test is the same as [test_linkat_file], but ensures that two different types can be used
934 /// as the path arguments.
935 fn test_linkat_pathtypes() {
936 use nix::fcntl::AtFlags;
937
938 let tempdir = tempdir().unwrap();
939 let oldfilename = "foo.txt";
940 let oldfilepath = tempdir.path().join(oldfilename);
941
942 let newfilename = "bar.txt";
943 let newfilepath = tempdir.path().join(newfilename);
944
945 // Create file
946 File::create(oldfilepath).unwrap();
947
948 // Get file descriptor for base directory
949 let dirfd =
950 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
951 .unwrap();
952
953 // Attempt hard link file at relative path
954 linkat(
955 &dirfd,
956 PathBuf::from(oldfilename).as_path(),
957 &dirfd,
958 newfilename,
959 AtFlags::AT_SYMLINK_FOLLOW,
960 )
961 .unwrap();
962 assert!(newfilepath.exists());
963 }
964
965 #[test]
966 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
967 fn test_linkat_olddirfd_none() {
968 use nix::fcntl::AtFlags;
969 use nix::fcntl::AT_FDCWD;
970
971 let _dr = crate::DirRestore::new();
972
973 let tempdir_oldfile = tempdir().unwrap();
974 let oldfilename = "foo.txt";
975 let oldfilepath = tempdir_oldfile.path().join(oldfilename);
976
977 let tempdir_newfile = tempdir().unwrap();
978 let newfilename = "bar.txt";
979 let newfilepath = tempdir_newfile.path().join(newfilename);
980
981 // Create file
982 File::create(oldfilepath).unwrap();
983
984 // Get file descriptor for base directory of new file
985 let dirfd = fcntl::open(
986 tempdir_newfile.path(),
987 fcntl::OFlag::empty(),
988 stat::Mode::empty(),
989 )
990 .unwrap();
991
992 // Attempt hard link file using curent working directory as relative path for old file path
993 chdir(tempdir_oldfile.path()).unwrap();
994 linkat(
995 AT_FDCWD,
996 oldfilename,
997 &dirfd,
998 newfilename,
999 AtFlags::AT_SYMLINK_FOLLOW,
1000 )
1001 .unwrap();
1002 assert!(newfilepath.exists());
1003 }
1004
1005 #[test]
1006 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
1007 fn test_linkat_newdirfd_none() {
1008 use nix::fcntl::AtFlags;
1009 use nix::fcntl::AT_FDCWD;
1010
1011 let _dr = crate::DirRestore::new();
1012
1013 let tempdir_oldfile = tempdir().unwrap();
1014 let oldfilename = "foo.txt";
1015 let oldfilepath = tempdir_oldfile.path().join(oldfilename);
1016
1017 let tempdir_newfile = tempdir().unwrap();
1018 let newfilename = "bar.txt";
1019 let newfilepath = tempdir_newfile.path().join(newfilename);
1020
1021 // Create file
1022 File::create(oldfilepath).unwrap();
1023
1024 // Get file descriptor for base directory of old file
1025 let dirfd = fcntl::open(
1026 tempdir_oldfile.path(),
1027 fcntl::OFlag::empty(),
1028 stat::Mode::empty(),
1029 )
1030 .unwrap();
1031
1032 // Attempt hard link file using current working directory as relative path for new file path
1033 chdir(tempdir_newfile.path()).unwrap();
1034 linkat(
1035 &dirfd,
1036 oldfilename,
1037 AT_FDCWD,
1038 newfilename,
1039 AtFlags::AT_SYMLINK_FOLLOW,
1040 )
1041 .unwrap();
1042 assert!(newfilepath.exists());
1043 }
1044
1045 #[test]
1046 #[cfg(not(any(apple_targets, target_os = "redox", target_os = "haiku")))]
1047 fn test_linkat_no_follow_symlink() {
1048 use nix::fcntl::AtFlags;
1049 use nix::fcntl::AT_FDCWD;
1050
1051 let _m = crate::CWD_LOCK.read();
1052
1053 let tempdir = tempdir().unwrap();
1054 let oldfilename = "foo.txt";
1055 let oldfilepath = tempdir.path().join(oldfilename);
1056
1057 let symoldfilename = "symfoo.txt";
1058 let symoldfilepath = tempdir.path().join(symoldfilename);
1059
1060 let newfilename = "nofollowsymbar.txt";
1061 let newfilepath = tempdir.path().join(newfilename);
1062
1063 // Create file
1064 File::create(&oldfilepath).unwrap();
1065
1066 // Create symlink to file
1067 symlinkat(&oldfilepath, AT_FDCWD, &symoldfilepath).unwrap();
1068
1069 // Get file descriptor for base directory
1070 let dirfd =
1071 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
1072 .unwrap();
1073
1074 // Attempt link symlink of file at relative path
1075 linkat(
1076 &dirfd,
1077 symoldfilename,
1078 &dirfd,
1079 newfilename,
1080 AtFlags::empty(),
1081 )
1082 .unwrap();
1083
1084 // Assert newfile is actually a symlink to oldfile.
1085 assert_eq!(
1086 readlink(&newfilepath).unwrap().to_str().unwrap(),
1087 oldfilepath.to_str().unwrap()
1088 );
1089 }
1090
1091 #[test]
1092 #[cfg(not(any(target_os = "redox", target_os = "haiku")))]
1093 fn test_linkat_follow_symlink() {
1094 use nix::fcntl::AtFlags;
1095 use nix::fcntl::AT_FDCWD;
1096
1097 let _m = crate::CWD_LOCK.read();
1098
1099 let tempdir = tempdir().unwrap();
1100 let oldfilename = "foo.txt";
1101 let oldfilepath = tempdir.path().join(oldfilename);
1102
1103 let symoldfilename = "symfoo.txt";
1104 let symoldfilepath = tempdir.path().join(symoldfilename);
1105
1106 let newfilename = "nofollowsymbar.txt";
1107 let newfilepath = tempdir.path().join(newfilename);
1108
1109 // Create file
1110 File::create(&oldfilepath).unwrap();
1111
1112 // Create symlink to file
1113 symlinkat(&oldfilepath, AT_FDCWD, &symoldfilepath).unwrap();
1114
1115 // Get file descriptor for base directory
1116 let dirfd =
1117 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
1118 .unwrap();
1119
1120 // Attempt link target of symlink of file at relative path
1121 linkat(
1122 &dirfd,
1123 symoldfilename,
1124 &dirfd,
1125 newfilename,
1126 AtFlags::AT_SYMLINK_FOLLOW,
1127 )
1128 .unwrap();
1129
1130 let newfilestat = stat::stat(&newfilepath).unwrap();
1131
1132 // Check the file type of the new link
1133 assert_eq!(
1134 stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t)
1135 & SFlag::S_IFMT,
1136 SFlag::S_IFREG
1137 );
1138
1139 // Check the number of hard links to the original file
1140 assert_eq!(newfilestat.st_nlink, 2);
1141 }
1142
1143 #[test]
1144 #[cfg(not(target_os = "redox"))]
1145 fn test_unlinkat_dir_noremovedir() {
1146 let tempdir = tempdir().unwrap();
1147 let dirname = "foo_dir";
1148 let dirpath = tempdir.path().join(dirname);
1149
1150 // Create dir
1151 DirBuilder::new().recursive(true).create(dirpath).unwrap();
1152
1153 // Get file descriptor for base directory
1154 let dirfd =
1155 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
1156 .unwrap();
1157
1158 // Attempt unlink dir at relative path without proper flag
1159 let err_result =
1160 unlinkat(&dirfd, dirname, UnlinkatFlags::NoRemoveDir).unwrap_err();
1161 assert!(err_result == Errno::EISDIR || err_result == Errno::EPERM);
1162 }
1163
1164 #[test]
1165 #[cfg(not(target_os = "redox"))]
1166 fn test_unlinkat_dir_removedir() {
1167 let tempdir = tempdir().unwrap();
1168 let dirname = "foo_dir";
1169 let dirpath = tempdir.path().join(dirname);
1170
1171 // Create dir
1172 DirBuilder::new().recursive(true).create(&dirpath).unwrap();
1173
1174 // Get file descriptor for base directory
1175 let dirfd =
1176 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
1177 .unwrap();
1178
1179 // Attempt unlink dir at relative path with proper flag
1180 unlinkat(&dirfd, dirname, UnlinkatFlags::RemoveDir).unwrap();
1181 assert!(!dirpath.exists());
1182 }
1183
1184 #[test]
1185 #[cfg(not(target_os = "redox"))]
1186 fn test_unlinkat_file() {
1187 let tempdir = tempdir().unwrap();
1188 let filename = "foo.txt";
1189 let filepath = tempdir.path().join(filename);
1190
1191 // Create file
1192 File::create(&filepath).unwrap();
1193
1194 // Get file descriptor for base directory
1195 let dirfd =
1196 fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty())
1197 .unwrap();
1198
1199 // Attempt unlink file at relative path
1200 unlinkat(&dirfd, filename, UnlinkatFlags::NoRemoveDir).unwrap();
1201 assert!(!filepath.exists());
1202 }
1203
1204 #[test]
1205 fn test_access_not_existing() {
1206 let tempdir = tempdir().unwrap();
1207 let dir = tempdir.path().join("does_not_exist.txt");
1208 assert_eq!(
1209 access(&dir, AccessFlags::F_OK).err().unwrap(),
1210 Errno::ENOENT
1211 );
1212 }
1213
1214 #[test]
1215 fn test_access_file_exists() {
1216 let tempdir = tempdir().unwrap();
1217 let path = tempdir.path().join("does_exist.txt");
1218 let _file = File::create(path.clone()).unwrap();
1219 access(&path, AccessFlags::R_OK | AccessFlags::W_OK)
1220 .expect("assertion failed");
1221 }
1222
1223 #[cfg(not(target_os = "redox"))]
1224 #[test]
1225 fn test_user_into_passwd() {
1226 let test_username = if cfg!(target_os = "haiku") {
1227 // "nobody" unavailable on haiku
1228 "user"
1229 } else if cfg!(target_os = "cygwin") {
1230 // the Windows admin user
1231 "Administrator"
1232 } else {
1233 // get the UID of the "nobody" user
1234 "nobody"
1235 };
1236
1237 let nobody = User::from_name(test_username).unwrap().unwrap();
1238 let pwd: libc::passwd = nobody.into();
1239 let _: User = (&pwd).into();
1240 }
1241
1242 /// Tests setting the filesystem UID with `setfsuid`.
1243 #[cfg(linux_android)]
1244 #[test]
1245 fn test_setfsuid() {
1246 use std::os::unix::fs::PermissionsExt;
1247 use std::{fs, io, thread};
1248 require_capability!("test_setfsuid", CAP_SETUID);
1249
1250 // get the UID of the "nobody" user
1251 let nobody = User::from_name("nobody").unwrap().unwrap();
1252
1253 // create a temporary file with permissions '-rw-r-----'
1254 let file = tempfile::NamedTempFile::new_in("/var/tmp").unwrap();
1255 let temp_path = file.into_temp_path();
1256 let temp_path_2 = temp_path.to_path_buf();
1257 let mut permissions = fs::metadata(&temp_path).unwrap().permissions();
1258 permissions.set_mode(0o640);
1259
1260 // spawn a new thread where to test setfsuid
1261 thread::spawn(move || {
1262 // set filesystem UID
1263 let fuid = setfsuid(nobody.uid);
1264 // trying to open the temporary file should fail with EACCES
1265 let res = fs::File::open(&temp_path);
1266 let err = res.expect_err("assertion failed");
1267 assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
1268
1269 // assert fuid actually changes
1270 let prev_fuid = setfsuid(Uid::from_raw(-1i32 as u32));
1271 assert_ne!(prev_fuid, fuid);
1272 })
1273 .join()
1274 .unwrap();
1275
1276 // open the temporary file with the current thread filesystem UID
1277 fs::File::open(temp_path_2).unwrap();
1278 }
1279
1280 #[test]
1281 #[cfg(not(any(
1282 target_os = "redox",
1283 target_os = "fuchsia",
1284 target_os = "haiku"
1285 )))]
1286 fn test_ttyname() {
1287 use std::os::fd::AsRawFd;
1288
1289 let fd = posix_openpt(OFlag::O_RDWR).expect("posix_openpt failed");
1290 assert!(fd.as_raw_fd() > 0);
1291
1292 // on linux, we can just call ttyname on the pty master directly, but
1293 // apparently osx requires that ttyname is called on a slave pty (can't
1294 // find this documented anywhere, but it seems to empirically be the case)
1295 grantpt(&fd).expect("grantpt failed");
1296 unlockpt(&fd).expect("unlockpt failed");
1297 let sname = unsafe { ptsname(&fd) }.expect("ptsname failed");
1298 let fds = fs::OpenOptions::new()
1299 .read(true)
1300 .write(true)
1301 .open(Path::new(&sname))
1302 .expect("open failed");
1303
1304 let name = ttyname(fds).expect("ttyname failed");
1305 assert!(name.starts_with("/dev"));
1306 }
1307
1308 #[test]
1309 #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))]
1310 fn test_ttyname_not_pty() {
1311 let fd = File::open("/dev/zero").unwrap();
1312 assert_eq!(ttyname(fd), Err(Errno::ENOTTY));
1313 }
1314
1315 #[test]
1316 #[cfg(bsd)]
1317 fn test_getpeereid() {
1318 use std::os::unix::net::UnixStream;
1319 let (sock_a, sock_b) = UnixStream::pair().unwrap();
1320
1321 let (uid_a, gid_a) = getpeereid(sock_a).unwrap();
1322 let (uid_b, gid_b) = getpeereid(sock_b).unwrap();
1323
1324 let uid = geteuid();
1325 let gid = getegid();
1326
1327 assert_eq!(uid, uid_a);
1328 assert_eq!(gid, gid_a);
1329 assert_eq!(uid_a, uid_b);
1330 assert_eq!(gid_a, gid_b);
1331 }
1332
1333 #[test]
1334 #[cfg(not(target_os = "redox"))]
1335 fn test_faccessat_none_not_existing() {
1336 use nix::fcntl::AtFlags;
1337 use nix::fcntl::AT_FDCWD;
1338
1339 let tempdir = tempfile::tempdir().unwrap();
1340 let dir = tempdir.path().join("does_not_exist.txt");
1341 assert_eq!(
1342 faccessat(AT_FDCWD, &dir, AccessFlags::F_OK, AtFlags::empty())
1343 .err()
1344 .unwrap(),
1345 Errno::ENOENT
1346 );
1347 }
1348
1349 #[test]
1350 #[cfg(not(target_os = "redox"))]
1351 fn test_faccessat_not_existing() {
1352 use nix::fcntl::AtFlags;
1353
1354 let tempdir = tempfile::tempdir().unwrap();
1355 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
1356 let not_exist_file = "does_not_exist.txt";
1357 assert_eq!(
1358 faccessat(&dirfd, not_exist_file, AccessFlags::F_OK, AtFlags::empty(),)
1359 .err()
1360 .unwrap(),
1361 Errno::ENOENT
1362 );
1363 }
1364
1365 #[test]
1366 #[cfg(not(target_os = "redox"))]
1367 fn test_faccessat_none_file_exists() {
1368 use nix::fcntl::AtFlags;
1369 use nix::fcntl::AT_FDCWD;
1370
1371 let tempdir = tempfile::tempdir().unwrap();
1372 let path = tempdir.path().join("does_exist.txt");
1373 let _file = File::create(path.clone()).unwrap();
1374 assert!(faccessat(
1375 AT_FDCWD,
1376 &path,
1377 AccessFlags::R_OK | AccessFlags::W_OK,
1378 AtFlags::empty(),
1379 )
1380 .is_ok());
1381 }
1382
1383 #[test]
1384 #[cfg(not(target_os = "redox"))]
1385 fn test_faccessat_file_exists() {
1386 use nix::fcntl::AtFlags;
1387
1388 let tempdir = tempfile::tempdir().unwrap();
1389 let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap();
1390 let exist_file = "does_exist.txt";
1391 let path = tempdir.path().join(exist_file);
1392 let _file = File::create(path.clone()).unwrap();
1393 assert!(faccessat(
1394 &dirfd,
1395 &path,
1396 AccessFlags::R_OK | AccessFlags::W_OK,
1397 AtFlags::empty(),
1398 )
1399 .is_ok());
1400 }
1401
1402 #[test]
1403 #[cfg(any(all(target_os = "linux", not(target_env = "uclibc")), freebsdlike))]
1404 fn test_eaccess_not_existing() {
1405 let tempdir = tempdir().unwrap();
1406 let dir = tempdir.path().join("does_not_exist.txt");
1407 assert_eq!(
1408 eaccess(&dir, AccessFlags::F_OK).err().unwrap(),
1409 Errno::ENOENT
1410 );
1411 }
1412
1413 #[test]
1414 #[cfg(any(all(target_os = "linux", not(target_env = "uclibc")), freebsdlike))]
1415 fn test_eaccess_file_exists() {
1416 let tempdir = tempdir().unwrap();
1417 let path = tempdir.path().join("does_exist.txt");
1418 let _file = File::create(path.clone()).unwrap();
1419 eaccess(&path, AccessFlags::R_OK | AccessFlags::W_OK)
1420 .expect("assertion failed");
1421 }
1422
1423 #[test]
1424 #[cfg(bsd)]
1425 fn test_group_from() {
1426 let group = Group::from_name("wheel").unwrap().unwrap();
1427 assert!(group.name == "wheel");
1428 let group_id = group.gid;
1429 let group = Group::from_gid(group_id).unwrap().unwrap();
1430 assert_eq!(group.gid, group_id);
1431 assert_eq!(group.name, "wheel");
1432 }