-
Notifications
You must be signed in to change notification settings - Fork 669
/
unistd.rs
3677 lines (3433 loc) · 124 KB
/
unistd.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
//! Safe wrappers around functions found in libc "unistd.h" header
use crate::errno::Errno;
#[cfg(any(
all(feature = "fs", not(target_os = "redox")),
all(feature = "process", linux_android)
))]
use crate::fcntl::at_rawfd;
#[cfg(not(target_os = "redox"))]
#[cfg(feature = "fs")]
use crate::fcntl::AtFlags;
#[cfg(feature = "fs")]
#[cfg(any(
linux_android,
freebsdlike,
solarish,
netbsdlike,
target_os = "emscripten",
target_os = "fuchsia",
target_os = "hurd",
target_os = "redox",
))]
use crate::fcntl::OFlag;
#[cfg(all(feature = "fs", bsd))]
use crate::sys::stat::FileFlag;
#[cfg(feature = "fs")]
use crate::sys::stat::Mode;
use crate::{Error, NixPath, Result};
#[cfg(not(target_os = "redox"))]
use cfg_if::cfg_if;
use libc::{
c_char, c_int, c_long, c_uint, gid_t, mode_t, off_t, pid_t, size_t, uid_t,
};
use std::convert::Infallible;
#[cfg(not(target_os = "redox"))]
use std::ffi::CString;
use std::ffi::{CStr, OsStr, OsString};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::io::{AsFd, AsRawFd, OwnedFd, RawFd};
use std::path::PathBuf;
use std::{fmt, mem, ptr};
feature! {
#![feature = "fs"]
#[cfg(linux_android)]
pub use self::pivot_root::*;
}
#[cfg(any(freebsdlike, linux_android, target_os = "openbsd"))]
pub use self::setres::*;
#[cfg(any(freebsdlike, linux_android, target_os = "openbsd"))]
pub use self::getres::*;
feature! {
#![feature = "user"]
/// User identifier
///
/// Newtype pattern around `uid_t` (which is just alias). It prevents bugs caused by accidentally
/// passing wrong value.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Uid(uid_t);
impl Uid {
/// Creates `Uid` from raw `uid_t`.
pub const fn from_raw(uid: uid_t) -> Self {
Uid(uid)
}
/// Returns Uid of calling process. This is practically a more Rusty alias for `getuid`.
#[doc(alias("getuid"))]
pub fn current() -> Self {
getuid()
}
/// Returns effective Uid of calling process. This is practically a more Rusty alias for `geteuid`.
#[doc(alias("geteuid"))]
pub fn effective() -> Self {
geteuid()
}
/// Returns true if the `Uid` represents privileged user - root. (If it equals zero.)
pub const fn is_root(self) -> bool {
self.0 == ROOT.0
}
/// Get the raw `uid_t` wrapped by `self`.
pub const fn as_raw(self) -> uid_t {
self.0
}
}
impl From<Uid> for uid_t {
fn from(uid: Uid) -> Self {
uid.0
}
}
impl From<uid_t> for Uid {
fn from(uid: uid_t) -> Self {
Uid(uid)
}
}
impl fmt::Display for Uid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
/// Constant for UID = 0
pub const ROOT: Uid = Uid(0);
/// Group identifier
///
/// Newtype pattern around `gid_t` (which is just alias). It prevents bugs caused by accidentally
/// passing wrong value.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Gid(gid_t);
impl Gid {
/// Creates `Gid` from raw `gid_t`.
pub const fn from_raw(gid: gid_t) -> Self {
Gid(gid)
}
/// Returns Gid of calling process. This is practically a more Rusty alias for `getgid`.
#[doc(alias("getgid"))]
pub fn current() -> Self {
getgid()
}
/// Returns effective Gid of calling process. This is practically a more Rusty alias for `getegid`.
#[doc(alias("getegid"))]
pub fn effective() -> Self {
getegid()
}
/// Get the raw `gid_t` wrapped by `self`.
pub const fn as_raw(self) -> gid_t {
self.0
}
}
impl From<Gid> for gid_t {
fn from(gid: Gid) -> Self {
gid.0
}
}
impl From<gid_t> for Gid {
fn from(gid: gid_t) -> Self {
Gid(gid)
}
}
impl fmt::Display for Gid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
}
feature! {
#![feature = "process"]
/// Process identifier
///
/// Newtype pattern around `pid_t` (which is just alias). It prevents bugs caused by accidentally
/// passing wrong value.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Pid(pid_t);
impl Pid {
/// Creates `Pid` from raw `pid_t`.
pub const fn from_raw(pid: pid_t) -> Self {
Pid(pid)
}
/// Returns PID of calling process
#[doc(alias("getpid"))]
pub fn this() -> Self {
getpid()
}
/// Returns PID of parent of calling process
#[doc(alias("getppid"))]
pub fn parent() -> Self {
getppid()
}
/// Get the raw `pid_t` wrapped by `self`.
pub const fn as_raw(self) -> pid_t {
self.0
}
}
impl From<Pid> for pid_t {
fn from(pid: Pid) -> Self {
pid.0
}
}
impl fmt::Display for Pid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
/// Represents the successful result of calling `fork`
///
/// When `fork` is called, the process continues execution in the parent process
/// and in the new child. This return type can be examined to determine whether
/// you are now executing in the parent process or in the child.
#[derive(Clone, Copy, Debug)]
pub enum ForkResult {
/// This is the parent process of the fork.
Parent {
/// The PID of the fork's child process
child: Pid
},
/// This is the child process of the fork.
Child,
}
impl ForkResult {
/// Return `true` if this is the child process of the `fork()`
#[inline]
pub fn is_child(self) -> bool {
matches!(self, ForkResult::Child)
}
/// Returns `true` if this is the parent process of the `fork()`
#[inline]
pub fn is_parent(self) -> bool {
!self.is_child()
}
}
/// Create a new child process duplicating the parent process ([see
/// fork(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html)).
///
/// After successfully calling the fork system call, a second process will
/// be created which is identical to the original except for the pid and the
/// return value of this function. As an example:
///
/// ```
/// use nix::{sys::wait::waitpid,unistd::{fork, ForkResult, write}};
///
/// match unsafe{fork()} {
/// Ok(ForkResult::Parent { child, .. }) => {
/// println!("Continuing execution in parent process, new child has pid: {}", child);
/// waitpid(child, None).unwrap();
/// }
/// Ok(ForkResult::Child) => {
/// // Unsafe to use `println!` (or `unwrap`) here. See Safety.
/// write(std::io::stdout(), "I'm a new child process\n".as_bytes()).ok();
/// unsafe { libc::_exit(0) };
/// }
/// Err(_) => println!("Fork failed"),
/// }
/// ```
///
/// This will print something like the following (order nondeterministic). The
/// thing to note is that you end up with two processes continuing execution
/// immediately after the fork call but with different match arms.
///
/// ```text
/// Continuing execution in parent process, new child has pid: 1234
/// I'm a new child process
/// ```
///
/// # Safety
///
/// In a multithreaded program, only [async-signal-safe] functions like `pause`
/// and `_exit` may be called by the child (the parent isn't restricted). Note
/// that memory allocation may **not** be async-signal-safe and thus must be
/// prevented.
///
/// Those functions are only a small subset of your operating system's API, so
/// special care must be taken to only invoke code you can control and audit.
///
/// [async-signal-safe]: https://man7.org/linux/man-pages/man7/signal-safety.7.html
#[inline]
pub unsafe fn fork() -> Result<ForkResult> {
use self::ForkResult::*;
let res = unsafe { libc::fork() };
Errno::result(res).map(|res| match res {
0 => Child,
res => Parent { child: Pid(res) },
})
}
/// Get the pid of this process (see
/// [getpid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpid.html)).
///
/// Since you are running code, there is always a pid to return, so there
/// is no error case that needs to be handled.
#[inline]
pub fn getpid() -> Pid {
Pid(unsafe { libc::getpid() })
}
/// Get the pid of this processes' parent (see
/// [getpid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getppid.html)).
///
/// There is always a parent pid to return, so there is no error case that needs
/// to be handled.
#[inline]
pub fn getppid() -> Pid {
Pid(unsafe { libc::getppid() }) // no error handling, according to man page: "These functions are always successful."
}
/// Set a process group ID (see
/// [setpgid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setpgid.html)).
///
/// Set the process group id (PGID) of a particular process. If a pid of zero
/// is specified, then the pid of the calling process is used. Process groups
/// may be used to group together a set of processes in order for the OS to
/// apply some operations across the group.
///
/// `setsid()` may be used to create a new process group.
#[inline]
pub fn setpgid(pid: Pid, pgid: Pid) -> Result<()> {
let res = unsafe { libc::setpgid(pid.into(), pgid.into()) };
Errno::result(res).map(drop)
}
/// Get process group
///
/// See Also [`getpgid`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgid.html)
#[inline]
pub fn getpgid(pid: Option<Pid>) -> Result<Pid> {
let res = unsafe { libc::getpgid(pid.unwrap_or(Pid(0)).into()) };
Errno::result(res).map(Pid)
}
/// Create new session and set process group id (see
/// [setsid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setsid.html)).
#[inline]
pub fn setsid() -> Result<Pid> {
Errno::result(unsafe { libc::setsid() }).map(Pid)
}
/// Get the process group ID of a session leader
/// [getsid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsid.html).
///
/// Obtain the process group ID of the process that is the session leader of the process specified
/// by pid. If pid is zero, it specifies the calling process.
#[inline]
#[cfg(not(target_os = "redox"))]
pub fn getsid(pid: Option<Pid>) -> Result<Pid> {
let res = unsafe { libc::getsid(pid.unwrap_or(Pid(0)).into()) };
Errno::result(res).map(Pid)
}
}
feature! {
#![all(feature = "process", feature = "term")]
/// Get the terminal foreground process group (see
/// [tcgetpgrp(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcgetpgrp.html)).
///
/// Get the group process id (GPID) of the foreground process group on the
/// terminal associated to file descriptor (FD).
#[inline]
pub fn tcgetpgrp<F: AsFd>(fd: F) -> Result<Pid> {
let res = unsafe { libc::tcgetpgrp(fd.as_fd().as_raw_fd()) };
Errno::result(res).map(Pid)
}
/// Set the terminal foreground process group (see
/// [tcgetpgrp(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcsetpgrp.html)).
///
/// Get the group process id (PGID) to the foreground process group on the
/// terminal associated to file descriptor (FD).
#[inline]
pub fn tcsetpgrp<F: AsFd>(fd: F, pgrp: Pid) -> Result<()> {
let res = unsafe { libc::tcsetpgrp(fd.as_fd().as_raw_fd(), pgrp.into()) };
Errno::result(res).map(drop)
}
}
feature! {
#![feature = "process"]
/// Get the group id of the calling process (see
///[getpgrp(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgrp.html)).
///
/// Get the process group id (PGID) of the calling process.
/// According to the man page it is always successful.
#[inline]
pub fn getpgrp() -> Pid {
Pid(unsafe { libc::getpgrp() })
}
/// Get the caller's thread ID (see
/// [gettid(2)](https://man7.org/linux/man-pages/man2/gettid.2.html).
///
/// This function is only available on Linux based systems. In a single
/// threaded process, the main thread will have the same ID as the process. In
/// a multithreaded process, each thread will have a unique thread id but the
/// same process ID.
///
/// No error handling is required as a thread id should always exist for any
/// process, even if threads are not being used.
#[cfg(linux_android)]
#[inline]
pub fn gettid() -> Pid {
Pid(unsafe { libc::syscall(libc::SYS_gettid) as pid_t })
}
}
feature! {
#![feature = "fs"]
/// Create a copy of the specified file descriptor (see
/// [dup(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup.html)).
///
/// The new file descriptor will have a new index but refer to the same
/// resource as the old file descriptor and the old and new file descriptors may
/// be used interchangeably. The new and old file descriptor share the same
/// underlying resource, offset, and file status flags. The actual index used
/// for the file descriptor will be the lowest fd index that is available.
///
/// The two file descriptors do not share file descriptor flags (e.g. `OFlag::FD_CLOEXEC`).
#[inline]
pub fn dup(oldfd: RawFd) -> Result<RawFd> {
let res = unsafe { libc::dup(oldfd) };
Errno::result(res)
}
/// Create a copy of the specified file descriptor using the specified fd (see
/// [dup(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup.html)).
///
/// This function behaves similar to `dup()` except that it will try to use the
/// specified fd instead of allocating a new one. See the man pages for more
/// detail on the exact behavior of this function.
#[inline]
pub fn dup2(oldfd: RawFd, newfd: RawFd) -> Result<RawFd> {
let res = unsafe { libc::dup2(oldfd, newfd) };
Errno::result(res)
}
/// Create a new copy of the specified file descriptor using the specified fd
/// and flags (see [`dup(2)`](https://man7.org/linux/man-pages/man2/dup.2.html)).
///
/// This function behaves similar to `dup2()` but allows for flags to be
/// specified.
#[cfg(any(
netbsdlike,
solarish,
target_os = "freebsd",
target_os = "fuchsia",
target_os = "hurd",
target_os = "linux"
))]
pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
let res = unsafe { libc::dup3(oldfd, newfd, flags.bits()) };
Errno::result(res)
}
/// Change the current working directory of the calling process (see
/// [chdir(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/chdir.html)).
///
/// This function may fail in a number of different scenarios. See the man
/// pages for additional details on possible failure cases.
#[inline]
pub fn chdir<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res =
path.with_nix_path(|cstr| unsafe { libc::chdir(cstr.as_ptr()) })?;
Errno::result(res).map(drop)
}
/// Change the current working directory of the process to the one
/// given as an open file descriptor (see
/// [fchdir(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchdir.html)).
///
/// This function may fail in a number of different scenarios. See the man
/// pages for additional details on possible failure cases.
#[inline]
#[cfg(not(target_os = "fuchsia"))]
pub fn fchdir(dirfd: RawFd) -> Result<()> {
let res = unsafe { libc::fchdir(dirfd) };
Errno::result(res).map(drop)
}
/// Creates new directory `path` with access rights `mode`. (see [mkdir(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdir.html))
///
/// # Errors
///
/// There are several situations where mkdir might fail:
///
/// - current user has insufficient rights in the parent directory
/// - the path already exists
/// - the path name is too long (longer than `PATH_MAX`, usually 4096 on linux, 1024 on OS X)
///
/// # Example
///
/// ```rust
/// use nix::unistd;
/// use nix::sys::stat;
/// use tempfile::tempdir;
///
/// let tmp_dir1 = tempdir().unwrap();
/// let tmp_dir2 = tmp_dir1.path().join("new_dir");
///
/// // create new directory and give read, write and execute rights to the owner
/// match unistd::mkdir(&tmp_dir2, stat::Mode::S_IRWXU) {
/// Ok(_) => println!("created {:?}", tmp_dir2),
/// Err(err) => println!("Error creating directory: {}", err),
/// }
/// ```
#[inline]
pub fn mkdir<P: ?Sized + NixPath>(path: &P, mode: Mode) -> Result<()> {
let res = path.with_nix_path(|cstr| unsafe {
libc::mkdir(cstr.as_ptr(), mode.bits() as mode_t)
})?;
Errno::result(res).map(drop)
}
/// Creates new fifo special file (named pipe) with path `path` and access rights `mode`.
///
/// # Errors
///
/// There are several situations where mkfifo might fail:
///
/// - current user has insufficient rights in the parent directory
/// - the path already exists
/// - the path name is too long (longer than `PATH_MAX`, usually 4096 on linux, 1024 on OS X)
///
/// For a full list consult
/// [posix specification](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkfifo.html)
///
/// # Example
///
/// ```rust
/// use nix::unistd;
/// use nix::sys::stat;
/// use tempfile::tempdir;
///
/// let tmp_dir = tempdir().unwrap();
/// let fifo_path = tmp_dir.path().join("foo.pipe");
///
/// // create new fifo and give read, write and execute rights to the owner
/// match unistd::mkfifo(&fifo_path, stat::Mode::S_IRWXU) {
/// Ok(_) => println!("created {:?}", fifo_path),
/// Err(err) => println!("Error creating fifo: {}", err),
/// }
/// ```
#[inline]
#[cfg(not(target_os = "redox"))] // RedoxFS does not support fifo yet
pub fn mkfifo<P: ?Sized + NixPath>(path: &P, mode: Mode) -> Result<()> {
let res = path.with_nix_path(|cstr| unsafe {
libc::mkfifo(cstr.as_ptr(), mode.bits() as mode_t)
})?;
Errno::result(res).map(drop)
}
/// Creates new fifo special file (named pipe) with path `path` and access rights `mode`.
///
/// If `dirfd` has a value, then `path` is relative to directory associated with the file descriptor.
///
/// If `dirfd` is `None`, then `path` is relative to the current working directory.
///
/// # References
///
/// [mkfifoat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkfifoat.html).
// mkfifoat is not implemented in OSX or android
#[inline]
#[cfg(not(any(
apple_targets,
target_os = "haiku",
target_os = "android",
target_os = "redox"
)))]
pub fn mkfifoat<P: ?Sized + NixPath>(
dirfd: Option<RawFd>,
path: &P,
mode: Mode,
) -> Result<()> {
let res = path.with_nix_path(|cstr| unsafe {
libc::mkfifoat(at_rawfd(dirfd), cstr.as_ptr(), mode.bits() as mode_t)
})?;
Errno::result(res).map(drop)
}
/// Creates a symbolic link at `path2` which points to `path1`.
///
/// If `dirfd` has a value, then `path2` is relative to directory associated
/// with the file descriptor.
///
/// If `dirfd` is `None`, then `path2` is relative to the current working
/// directory. This is identical to `libc::symlink(path1, path2)`.
///
/// See also [symlinkat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/symlinkat.html).
#[cfg(not(target_os = "redox"))]
pub fn symlinkat<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
path1: &P1,
dirfd: Option<RawFd>,
path2: &P2,
) -> Result<()> {
let res = path1.with_nix_path(|path1| {
path2.with_nix_path(|path2| unsafe {
libc::symlinkat(
path1.as_ptr(),
dirfd.unwrap_or(libc::AT_FDCWD),
path2.as_ptr(),
)
})
})??;
Errno::result(res).map(drop)
}
}
// Double the buffer capacity up to limit. In case it already has
// reached the limit, return Errno::ERANGE.
#[cfg(any(feature = "fs", feature = "user"))]
fn reserve_double_buffer_size<T>(buf: &mut Vec<T>, limit: usize) -> Result<()> {
use std::cmp::min;
if buf.capacity() >= limit {
return Err(Errno::ERANGE);
}
let capacity = min(buf.capacity() * 2, limit);
buf.reserve(capacity);
Ok(())
}
feature! {
#![feature = "fs"]
/// Returns the current directory as a `PathBuf`
///
/// Err is returned if the current user doesn't have the permission to read or search a component
/// of the current path.
///
/// # Example
///
/// ```rust
/// use nix::unistd;
///
/// // assume that we are allowed to get current directory
/// let dir = unistd::getcwd().unwrap();
/// println!("The current directory is {:?}", dir);
/// ```
#[inline]
pub fn getcwd() -> Result<PathBuf> {
let mut buf = Vec::<u8>::with_capacity(512);
loop {
unsafe {
let ptr = buf.as_mut_ptr().cast();
// The buffer must be large enough to store the absolute pathname plus
// a terminating null byte, or else null is returned.
// To safely handle this we start with a reasonable size (512 bytes)
// and double the buffer size upon every error
if !libc::getcwd(ptr, buf.capacity()).is_null() {
let len = CStr::from_ptr(buf.as_ptr().cast())
.to_bytes()
.len();
buf.set_len(len);
buf.shrink_to_fit();
return Ok(PathBuf::from(OsString::from_vec(buf)));
} else {
let error = Errno::last();
// ERANGE means buffer was too small to store directory name
if error != Errno::ERANGE {
return Err(error);
}
}
#[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
// Trigger the internal buffer resizing logic.
reserve_double_buffer_size(&mut buf, PATH_MAX)?;
}
}
}
}
feature! {
#![all(feature = "user", feature = "fs")]
/// Computes the raw UID and GID values to pass to a `*chown` call.
// The cast is not unnecessary on all platforms.
#[allow(clippy::unnecessary_cast)]
fn chown_raw_ids(owner: Option<Uid>, group: Option<Gid>) -> (uid_t, gid_t) {
// According to the POSIX specification, -1 is used to indicate that owner and group
// are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap
// around to get -1.
let uid = owner
.map(Into::into)
.unwrap_or_else(|| (0 as uid_t).wrapping_sub(1));
let gid = group
.map(Into::into)
.unwrap_or_else(|| (0 as gid_t).wrapping_sub(1));
(uid, gid)
}
/// Change the ownership of the file at `path` to be owned by the specified
/// `owner` (user) and `group` (see
/// [chown(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/chown.html)).
///
/// The owner/group for the provided path name will not be modified if `None` is
/// provided for that argument. Ownership change will be attempted for the path
/// only if `Some` owner/group is provided.
#[inline]
pub fn chown<P: ?Sized + NixPath>(
path: &P,
owner: Option<Uid>,
group: Option<Gid>,
) -> Result<()> {
let res = path.with_nix_path(|cstr| {
let (uid, gid) = chown_raw_ids(owner, group);
unsafe { libc::chown(cstr.as_ptr(), uid, gid) }
})?;
Errno::result(res).map(drop)
}
/// Change the ownership of the file referred to by the open file descriptor `fd` to be owned by
/// the specified `owner` (user) and `group` (see
/// [fchown(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchown.html)).
///
/// The owner/group for the provided file will not be modified if `None` is
/// provided for that argument. Ownership change will be attempted for the path
/// only if `Some` owner/group is provided.
#[inline]
pub fn fchown(fd: RawFd, owner: Option<Uid>, group: Option<Gid>) -> Result<()> {
let (uid, gid) = chown_raw_ids(owner, group);
let res = unsafe { libc::fchown(fd, uid, gid) };
Errno::result(res).map(drop)
}
// Just a wrapper around `AtFlags` so that we can help our users migrate.
#[allow(missing_docs)]
#[cfg(not(target_os = "redox"))]
pub type FchownatFlags = AtFlags;
#[allow(missing_docs)]
#[cfg(not(target_os = "redox"))]
impl FchownatFlags {
#[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")]
#[allow(non_upper_case_globals)]
pub const FollowSymlink: FchownatFlags = FchownatFlags::empty();
#[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")]
#[allow(non_upper_case_globals)]
pub const NoFollowSymlink: FchownatFlags = FchownatFlags::AT_SYMLINK_NOFOLLOW;
}
/// Change the ownership of the file at `path` to be owned by the specified
/// `owner` (user) and `group`.
///
/// The owner/group for the provided path name will not be modified if `None` is
/// provided for that argument. Ownership change will be attempted for the path
/// only if `Some` owner/group is provided.
///
/// The file to be changed is determined relative to the directory associated
/// with the file descriptor `dirfd` or the current working directory
/// if `dirfd` is `None`.
///
/// If `flag` is `AtFlags::AT_SYMLINK_NOFOLLOW` and `path` names a symbolic link,
/// then the mode of the symbolic link is changed.
///
/// `fchownat(None, path, owner, group, AtFlags::AT_SYMLINK_NOFOLLOW)` is identical to
/// a call `libc::lchown(path, owner, group)`. That's why `lchown` is unimplemented in
/// the `nix` crate.
///
/// # References
///
/// [fchownat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchownat.html).
#[cfg(not(target_os = "redox"))]
pub fn fchownat<P: ?Sized + NixPath>(
dirfd: Option<RawFd>,
path: &P,
owner: Option<Uid>,
group: Option<Gid>,
flag: AtFlags,
) -> Result<()> {
let res = path.with_nix_path(|cstr| unsafe {
let (uid, gid) = chown_raw_ids(owner, group);
libc::fchownat(
at_rawfd(dirfd),
cstr.as_ptr(),
uid,
gid,
flag.bits()
)
})?;
Errno::result(res).map(drop)
}
}
feature! {
#![feature = "process"]
fn to_exec_array<S: AsRef<CStr>>(args: &[S]) -> Vec<*const c_char> {
use std::iter::once;
args.iter()
.map(|s| s.as_ref().as_ptr())
.chain(once(ptr::null()))
.collect()
}
/// Replace the current process image with a new one (see
/// [exec(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)).
///
/// See the `::nix::unistd::execve` system call for additional details. `execv`
/// performs the same action but does not allow for customization of the
/// environment for the new process.
#[inline]
pub fn execv<S: AsRef<CStr>>(path: &CStr, argv: &[S]) -> Result<Infallible> {
let args_p = to_exec_array(argv);
unsafe { libc::execv(path.as_ptr(), args_p.as_ptr()) };
Err(Errno::last())
}
/// Replace the current process image with a new one (see
/// [execve(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)).
///
/// The execve system call allows for another process to be "called" which will
/// replace the current process image. That is, this process becomes the new
/// command that is run. On success, this function will not return. Instead,
/// the new program will run until it exits.
///
/// `::nix::unistd::execv` and `::nix::unistd::execve` take as arguments a slice
/// of `::std::ffi::CString`s for `args` and `env` (for `execve`). Each element
/// in the `args` list is an argument to the new process. Each element in the
/// `env` list should be a string in the form "key=value".
#[inline]
pub fn execve<SA: AsRef<CStr>, SE: AsRef<CStr>>(
path: &CStr,
args: &[SA],
env: &[SE],
) -> Result<Infallible> {
let args_p = to_exec_array(args);
let env_p = to_exec_array(env);
unsafe { libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr()) };
Err(Errno::last())
}
/// Replace the current process image with a new one and replicate shell `PATH`
/// searching behavior (see
/// [exec(3)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)).
///
/// See `::nix::unistd::execve` for additional details. `execvp` behaves the
/// same as execv except that it will examine the `PATH` environment variables
/// for file names not specified with a leading slash. For example, `execv`
/// would not work if "bash" was specified for the path argument, but `execvp`
/// would assuming that a bash executable was on the system `PATH`.
#[inline]
pub fn execvp<S: AsRef<CStr>>(
filename: &CStr,
args: &[S],
) -> Result<Infallible> {
let args_p = to_exec_array(args);
unsafe { libc::execvp(filename.as_ptr(), args_p.as_ptr()) };
Err(Errno::last())
}
/// Replace the current process image with a new one and replicate shell `PATH`
/// searching behavior (see
/// [`execvpe(3)`](https://man7.org/linux/man-pages/man3/exec.3.html)).
///
/// This functions like a combination of `execvp(2)` and `execve(2)` to pass an
/// environment and have a search path. See these two for additional
/// information.
#[cfg(any(target_os = "haiku", target_os = "hurd", target_os = "linux", target_os = "openbsd"))]
pub fn execvpe<SA: AsRef<CStr>, SE: AsRef<CStr>>(
filename: &CStr,
args: &[SA],
env: &[SE],
) -> Result<Infallible> {
let args_p = to_exec_array(args);
let env_p = to_exec_array(env);
unsafe {
libc::execvpe(filename.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Errno::last())
}
/// Replace the current process image with a new one (see
/// [fexecve(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fexecve.html)).
///
/// The `fexecve` function allows for another process to be "called" which will
/// replace the current process image. That is, this process becomes the new
/// command that is run. On success, this function will not return. Instead,
/// the new program will run until it exits.
///
/// This function is similar to `execve`, except that the program to be executed
/// is referenced as a file descriptor instead of a path.
#[cfg(any(linux_android, freebsdlike, target_os = "hurd"))]
#[inline]
pub fn fexecve<SA: AsRef<CStr>, SE: AsRef<CStr>>(
fd: RawFd,
args: &[SA],
env: &[SE],
) -> Result<Infallible> {
let args_p = to_exec_array(args);
let env_p = to_exec_array(env);
unsafe { libc::fexecve(fd, args_p.as_ptr(), env_p.as_ptr()) };
Err(Errno::last())
}
/// Execute program relative to a directory file descriptor (see
/// [execveat(2)](https://man7.org/linux/man-pages/man2/execveat.2.html)).
///
/// The `execveat` function allows for another process to be "called" which will
/// replace the current process image. That is, this process becomes the new
/// command that is run. On success, this function will not return. Instead,
/// the new program will run until it exits.
///
/// This function is similar to `execve`, except that the program to be executed
/// is referenced as a file descriptor to the base directory plus a path.
#[cfg(linux_android)]
#[inline]
pub fn execveat<SA: AsRef<CStr>, SE: AsRef<CStr>>(
dirfd: Option<RawFd>,
pathname: &CStr,
args: &[SA],
env: &[SE],
flags: super::fcntl::AtFlags,
) -> Result<Infallible> {
let dirfd = at_rawfd(dirfd);
let args_p = to_exec_array(args);
let env_p = to_exec_array(env);
unsafe {
libc::syscall(
libc::SYS_execveat,
dirfd,
pathname.as_ptr(),
args_p.as_ptr(),
env_p.as_ptr(),
flags,
);
};
Err(Errno::last())
}
/// Daemonize this process by detaching from the controlling terminal (see
/// [daemon(3)](https://man7.org/linux/man-pages/man3/daemon.3.html)).
///
/// When a process is launched it is typically associated with a parent and it,
/// in turn, by its controlling terminal/process. In order for a process to run
/// in the "background" it must daemonize itself by detaching itself. Under
/// posix, this is done by doing the following:
///
/// 1. Parent process (this one) forks
/// 2. Parent process exits
/// 3. Child process continues to run.
///
/// `nochdir`:
///
/// * `nochdir = true`: The current working directory after daemonizing will
/// be the current working directory.
/// * `nochdir = false`: The current working directory after daemonizing will
/// be the root direcory, `/`.
///
/// `noclose`:
///
/// * `noclose = true`: The process' current stdin, stdout, and stderr file
/// descriptors will remain identical after daemonizing.
/// * `noclose = false`: The process' stdin, stdout, and stderr will point to
/// `/dev/null` after daemonizing.
#[cfg(any(
linux_android,
freebsdlike,
solarish,
netbsdlike
))]
pub fn daemon(nochdir: bool, noclose: bool) -> Result<()> {
let res = unsafe { libc::daemon(nochdir as c_int, noclose as c_int) };
Errno::result(res).map(drop)
}
}
feature! {