]> git.proxmox.com Git - proxmox-backup.git/blame - src/tools.rs
proxy: allow .key/.pem files instead of a pkcs12/.pfx file
[proxmox-backup.git] / src / tools.rs
CommitLineData
51b499db
DM
1//! Tools and utilities
2//!
3//! This is a collection of small and useful tools.
f12f8ff1
DM
4use failure::*;
5use nix::unistd;
6use nix::sys::stat;
7
74a69302
DM
8use lazy_static::lazy_static;
9
365bb90f 10use std::fs::{File, OpenOptions};
f12f8ff1
DM
11use std::io::Write;
12use std::path::Path;
43eeef28
DM
13use std::io::Read;
14use std::io::ErrorKind;
1628a4c7 15use std::time::Duration;
f12f8ff1 16
d96bb7f1 17use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
365bb90f 18
496a6784
DM
19use std::collections::HashMap;
20
af926291 21use serde_json::Value;
0fe5d605 22
8cf6e764 23pub mod timer;
7f0d67cf 24pub mod wrapped_reader_stream;
8f973f81
DM
25#[macro_use]
26pub mod common_regex;
8d04280b 27pub mod ticket;
6ed25cbe 28pub mod borrow;
b4d5787d 29pub mod fs;
c9b296f1 30pub mod tty;
f54c1998 31pub mod signalfd;
dce94d0e 32pub mod daemon;
3c2012f9 33pub mod procfs;
897982e2
WB
34pub mod read;
35pub mod write;
8cf6e764 36
a650f503
DM
37mod process_locker;
38pub use process_locker::*;
39
3b151414
DM
40#[macro_use]
41mod file_logger;
42pub use file_logger::*;
43
e80503d2
DM
44/// Macro to write error-handling blocks (like perl eval {})
45///
46/// #### Example:
47/// ```
fe651dd6
DM
48/// # #[macro_use] extern crate proxmox_backup;
49/// # use failure::*;
50/// # let some_condition = false;
e80503d2
DM
51/// let result = try_block!({
52/// if (some_condition) {
53/// bail!("some error");
54/// }
55/// Ok(())
56/// })
57/// .map_err(|e| format_err!("my try block returned an error - {}", e));
58/// ```
59
f0dbba8c
DM
60#[macro_export]
61macro_rules! try_block {
62 { $($token:tt)* } => {{ (|| -> Result<_,_> { $($token)* })() }}
63}
64
5d14eb6a 65
fded74d0 66/// The `BufferedRead` trait provides a single function
0a72e267
DM
67/// `buffered_read`. It returns a reference to an internal buffer. The
68/// purpose of this traid is to avoid unnecessary data copies.
fded74d0 69pub trait BufferedRead {
318564ac
DM
70 /// This functions tries to fill the internal buffers, then
71 /// returns a reference to the available data. It returns an empty
72 /// buffer if `offset` points to the end of the file.
0a72e267
DM
73 fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>;
74}
75
51b499db
DM
76/// Directly map a type into a binary buffer. This is mostly useful
77/// for reading structured data from a byte stream (file). You need to
78/// make sure that the buffer location does not change, so please
79/// avoid vec resize while you use such map.
80///
81/// This function panics if the buffer is not large enough.
50ea4396 82pub fn map_struct<T>(buffer: &[u8]) -> Result<&T, Error> {
dc3de618
DM
83 if buffer.len() < ::std::mem::size_of::<T>() {
84 bail!("unable to map struct - buffer too small");
85 }
95bd5dfe 86 Ok(unsafe { & * (buffer.as_ptr() as *const T) })
dc3de618
DM
87}
88
51b499db
DM
89/// Directly map a type into a mutable binary buffer. This is mostly
90/// useful for writing structured data into a byte stream (file). You
91/// need to make sure that the buffer location does not change, so
92/// please avoid vec resize while you use such map.
93///
94/// This function panics if the buffer is not large enough.
50ea4396 95pub fn map_struct_mut<T>(buffer: &mut [u8]) -> Result<&mut T, Error> {
dc3de618
DM
96 if buffer.len() < ::std::mem::size_of::<T>() {
97 bail!("unable to map struct - buffer too small");
98 }
95bd5dfe 99 Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) })
dc3de618
DM
100}
101
6235a418 102pub fn file_read_firstline<P: AsRef<Path>>(path: P) -> Result<String, Error> {
447787ab
DM
103
104 let path = path.as_ref();
105
6235a418
DM
106 try_block!({
107 let file = std::fs::File::open(path)?;
447787ab 108
6235a418 109 use std::io::{BufRead, BufReader};
447787ab 110
6235a418 111 let mut reader = BufReader::new(file);
447787ab 112
6235a418 113 let mut line = String::new();
447787ab 114
6235a418 115 let _ = reader.read_line(&mut line)?;
447787ab 116
6235a418
DM
117 Ok(line)
118 }).map_err(|err: Error| format_err!("unable to read {:?} - {}", path, err))
447787ab
DM
119}
120
12400210
DM
121pub fn file_get_contents<P: AsRef<Path>>(path: P) -> Result<Vec<u8>, Error> {
122
123 let path = path.as_ref();
124
125 try_block!({
126 std::fs::read(path)
127 }).map_err(|err| format_err!("unable to read {:?} - {}", path, err))
53157ca6
DM
128}
129
49cf9f3d 130pub fn file_get_json<P: AsRef<Path>>(path: P, default: Option<Value>) -> Result<Value, Error> {
53cafb59
DM
131
132 let path = path.as_ref();
133
49cf9f3d
DM
134 let raw = match std::fs::read(path) {
135 Ok(v) => v,
136 Err(err) => {
137 if err.kind() == std::io::ErrorKind::NotFound {
138 if let Some(v) = default {
139 return Ok(v);
140 }
141 }
142 bail!("unable to read json {:?} - {}", path, err);
143 }
144 };
53cafb59
DM
145
146 try_block!({
147 let data = String::from_utf8(raw)?;
148 let json = serde_json::from_str(&data)?;
149 Ok(json)
49cf9f3d 150 }).map_err(|err: Error| format_err!("unable to parse json from {:?} - {}", path, err))
53cafb59
DM
151}
152
eea81319
DM
153/// Atomically write a file
154///
155/// We first create a temporary file, which is then renamed.
f12f8ff1
DM
156pub fn file_set_contents<P: AsRef<Path>>(
157 path: P,
158 data: &[u8],
159 perm: Option<stat::Mode>,
160) -> Result<(), Error> {
eea81319
DM
161 file_set_contents_full(path, data, perm, None, None)
162}
163
164/// Atomically write a file with owner and group
165pub fn file_set_contents_full<P: AsRef<Path>>(
166 path: P,
167 data: &[u8],
168 perm: Option<stat::Mode>,
1619a720
DM
169 owner: Option<unistd::Uid>,
170 group: Option<unistd::Gid>,
eea81319 171) -> Result<(), Error> {
f12f8ff1
DM
172
173 let path = path.as_ref();
174
d64d80d2
DM
175 // Note: we use mkstemp heŕe, because this worka with different
176 // processes, threads, and even tokio tasks.
f12f8ff1
DM
177 let mut template = path.to_owned();
178 template.set_extension("tmp_XXXXXX");
179 let (fd, tmp_path) = match unistd::mkstemp(&template) {
180 Ok((fd, path)) => (fd, path),
181 Err(err) => bail!("mkstemp {:?} failed: {}", template, err),
182 };
183
184 let tmp_path = tmp_path.as_path();
185
1a7bc3dd 186 let mode : stat::Mode = perm.unwrap_or(stat::Mode::from(
f12f8ff1
DM
187 stat::Mode::S_IRUSR | stat::Mode::S_IWUSR |
188 stat::Mode::S_IRGRP | stat::Mode::S_IROTH
1a7bc3dd 189 ));
f12f8ff1
DM
190
191 if let Err(err) = stat::fchmod(fd, mode) {
192 let _ = unistd::unlink(tmp_path);
193 bail!("fchmod {:?} failed: {}", tmp_path, err);
194 }
195
eea81319
DM
196 if owner != None || group != None {
197 if let Err(err) = fchown(fd, owner, group) {
198 let _ = unistd::unlink(tmp_path);
199 bail!("fchown {:?} failed: {}", tmp_path, err);
200 }
201 }
202
f12f8ff1
DM
203 use std::os::unix::io::FromRawFd;
204 let mut file = unsafe { File::from_raw_fd(fd) };
205
206 if let Err(err) = file.write_all(data) {
207 let _ = unistd::unlink(tmp_path);
208 bail!("write failed: {}", err);
209 }
210
211 if let Err(err) = std::fs::rename(tmp_path, path) {
212 let _ = unistd::unlink(tmp_path);
213 bail!("Atomic rename failed for file {:?} - {}", path, err);
214 }
215
216 Ok(())
217}
43eeef28 218
51b499db
DM
219/// Create a file lock using fntl. This function allows you to specify
220/// a timeout if you want to avoid infinite blocking.
1628a4c7
WB
221pub fn lock_file<F: AsRawFd>(
222 file: &mut F,
223 exclusive: bool,
224 timeout: Option<Duration>,
eb90c9e3 225) -> Result<(), Error> {
1628a4c7
WB
226 let lockarg =
227 if exclusive {
228 nix::fcntl::FlockArg::LockExclusive
229 } else {
230 nix::fcntl::FlockArg::LockShared
231 };
232
233 let timeout = match timeout {
234 None => {
235 nix::fcntl::flock(file.as_raw_fd(), lockarg)?;
236 return Ok(());
237 }
238 Some(t) => t,
239 };
240
241 // unblock the timeout signal temporarily
242 let _sigblock_guard = timer::unblock_timeout_signal();
243
244 // setup a timeout timer
245 let mut timer = timer::Timer::create(
246 timer::Clock::Realtime,
247 timer::TimerEvent::ThisThreadSignal(timer::SIGTIMEOUT))?;
248
249 timer.arm(timer::TimerSpec::new()
250 .value(Some(timeout))
251 .interval(Some(Duration::from_millis(10))))?;
252
253 nix::fcntl::flock(file.as_raw_fd(), lockarg)?;
254 Ok(())
255}
365bb90f 256
51b499db
DM
257/// Open or create a lock file (append mode). Then try to
258/// aquire a lock using `lock_file()`.
1628a4c7
WB
259pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration)
260 -> Result<File, Error>
261{
262 let path = path.as_ref();
263 let mut file =
264 match OpenOptions::new()
265 .create(true)
266 .append(true)
267 .open(path)
268 {
365bb90f
DM
269 Ok(file) => file,
270 Err(err) => bail!("Unable to open lock {:?} - {}",
271 path, err),
272 };
28b96b56
DM
273 match lock_file(&mut file, true, Some(timeout)) {
274 Ok(_) => Ok(file),
275 Err(err) => bail!("Unable to aquire lock {:?} - {}",
276 path, err),
277 }
365bb90f
DM
278}
279
51b499db
DM
280/// Split a file into equal sized chunks. The last chunk may be
281/// smaller. Note: We cannot implement an `Iterator`, because iterators
282/// cannot return a borrowed buffer ref (we want zero-copy)
43eeef28
DM
283pub fn file_chunker<C, R>(
284 mut file: R,
285 chunk_size: usize,
606ce64b 286 mut chunk_cb: C
43eeef28 287) -> Result<(), Error>
606ce64b 288 where C: FnMut(usize, &[u8]) -> Result<bool, Error>,
43eeef28
DM
289 R: Read,
290{
291
292 const READ_BUFFER_SIZE: usize = 4*1024*1024; // 4M
293
294 if chunk_size > READ_BUFFER_SIZE { bail!("chunk size too large!"); }
295
296 let mut buf = vec![0u8; READ_BUFFER_SIZE];
297
298 let mut pos = 0;
299 let mut file_pos = 0;
300 loop {
301 let mut eof = false;
302 let mut tmp = &mut buf[..];
303 // try to read large portions, at least chunk_size
304 while pos < chunk_size {
305 match file.read(tmp) {
306 Ok(0) => { eof = true; break; },
307 Ok(n) => {
308 pos += n;
309 if pos > chunk_size { break; }
310 tmp = &mut tmp[n..];
311 }
312 Err(ref e) if e.kind() == ErrorKind::Interrupted => { /* try again */ }
5f0c2d56 313 Err(e) => bail!("read chunk failed - {}", e.to_string()),
43eeef28
DM
314 }
315 }
43eeef28
DM
316 let mut start = 0;
317 while start + chunk_size <= pos {
318 if !(chunk_cb)(file_pos, &buf[start..start+chunk_size])? { break; }
319 file_pos += chunk_size;
320 start += chunk_size;
321 }
322 if eof {
323 if start < pos {
324 (chunk_cb)(file_pos, &buf[start..pos])?;
325 //file_pos += pos - start;
326 }
327 break;
328 } else {
329 let rest = pos - start;
330 if rest > 0 {
331 let ptr = buf.as_mut_ptr();
332 unsafe { std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest); }
333 pos = rest;
334 } else {
335 pos = 0;
336 }
337 }
338 }
339
340 Ok(())
43eeef28 341}
0fe5d605 342
eea81319 343/// Returns the Unix uid/gid for the sepcified system user.
5d14eb6a
DM
344pub fn getpwnam_ugid(username: &str) -> Result<(libc::uid_t,libc::gid_t), Error> {
345 let info = unsafe { libc::getpwnam(std::ffi::CString::new(username).unwrap().as_ptr()) };
346 if info == std::ptr::null_mut() {
347 bail!("getwpnam '{}' failed", username);
348 }
349
350 let info = unsafe { *info };
351
352 Ok((info.pw_uid, info.pw_gid))
353}
354
35950380
DM
355/// Creates directory at the provided path with specified ownership
356///
357/// Simply returns if the directory already exists.
1619a720
DM
358pub fn create_dir_chown<P: AsRef<Path>>(
359 path: P,
360 perm: Option<stat::Mode>,
361 owner: Option<unistd::Uid>,
362 group: Option<unistd::Gid>,
35950380 363) -> Result<(), nix::Error>
1619a720 364{
35950380 365 let mode : stat::Mode = perm.unwrap_or(stat::Mode::from_bits_truncate(0o770));
1619a720
DM
366
367 let path = path.as_ref();
368
35950380
DM
369 match nix::unistd::mkdir(path, mode) {
370 Ok(()) => {},
371 Err(nix::Error::Sys(nix::errno::Errno::EEXIST)) => {
372 return Ok(());
373 },
374 err => return err,
375 }
376
1619a720
DM
377 unistd::chown(path, owner, group)?;
378
379 Ok(())
380}
381
eea81319
DM
382/// Change ownership of an open file handle
383pub fn fchown(
384 fd: RawFd,
385 owner: Option<nix::unistd::Uid>,
386 group: Option<nix::unistd::Gid>
387) -> Result<(), Error> {
388
389 // According to the POSIX specification, -1 is used to indicate that owner and group
390 // are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap
391 // around to get -1 (copied fron nix crate).
392 let uid = owner.map(Into::into).unwrap_or((0 as libc::uid_t).wrapping_sub(1));
393 let gid = group.map(Into::into).unwrap_or((0 as libc::gid_t).wrapping_sub(1));
394
395 let res = unsafe { libc::fchown(fd, uid, gid) };
396 nix::errno::Errno::result(res)?;
397
398 Ok(())
399}
400
5d14eb6a 401// Returns the hosts node name (UTS node name)
74a69302
DM
402pub fn nodename() -> &'static str {
403
404 lazy_static!{
405 static ref NODENAME: String = {
406
0d38dcb4
DM
407 nix::sys::utsname::uname()
408 .nodename()
409 .split('.')
410 .next()
411 .unwrap()
412 .to_owned()
74a69302
DM
413 };
414 }
415
416 &NODENAME
417}
418
f5f13ebc
DM
419pub fn json_object_to_query(data: Value) -> Result<String, Error> {
420
421 let mut query = url::form_urlencoded::Serializer::new(String::new());
422
423 let object = data.as_object().ok_or_else(|| {
424 format_err!("json_object_to_query: got wrong data type (expected object).")
425 })?;
426
427 for (key, value) in object {
428 match value {
429 Value::Bool(b) => { query.append_pair(key, &b.to_string()); }
430 Value::Number(n) => { query.append_pair(key, &n.to_string()); }
431 Value::String(s) => { query.append_pair(key, &s); }
432 Value::Array(arr) => {
433 for element in arr {
434 match element {
435 Value::Bool(b) => { query.append_pair(key, &b.to_string()); }
436 Value::Number(n) => { query.append_pair(key, &n.to_string()); }
437 Value::String(s) => { query.append_pair(key, &s); }
438 _ => bail!("json_object_to_query: unable to handle complex array data types."),
439 }
440 }
441 }
442 _ => bail!("json_object_to_query: unable to handle complex data types."),
443 }
444 }
445
446 Ok(query.finish())
447}
448
0fe5d605
DM
449pub fn required_string_param<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> {
450 match param[name].as_str() {
451 Some(s) => Ok(s),
452 None => bail!("missing parameter '{}'", name),
453 }
454}
0d38dcb4
DM
455
456pub fn required_integer_param<'a>(param: &'a Value, name: &str) -> Result<i64, Error> {
457 match param[name].as_i64() {
458 Some(s) => Ok(s),
459 None => bail!("missing parameter '{}'", name),
f8dfbb45
DM
460 }
461}
462
463pub fn required_array_param<'a>(param: &'a Value, name: &str) -> Result<Vec<Value>, Error> {
464 match param[name].as_array() {
465 Some(s) => Ok(s.to_vec()),
466 None => bail!("missing parameter '{}'", name),
0d38dcb4
DM
467 }
468}
383e8577 469
496a6784 470pub fn complete_file_name(arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
383e8577
DM
471
472 let mut result = vec![];
473
474 use nix::fcntl::OFlag;
475 use nix::sys::stat::Mode;
476 use nix::fcntl::AtFlags;
477
806500cd 478 let mut dirname = std::path::PathBuf::from(if arg.len() == 0 { "./" } else { arg });
383e8577
DM
479
480 let is_dir = match nix::sys::stat::fstatat(libc::AT_FDCWD, &dirname, AtFlags::empty()) {
481 Ok(stat) => (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR,
482 Err(_) => false,
483 };
484
485 if !is_dir {
486 if let Some(parent) = dirname.parent() {
487 dirname = parent.to_owned();
488 }
489 }
490
491 let mut dir = match nix::dir::Dir::openat(libc::AT_FDCWD, &dirname, OFlag::O_DIRECTORY, Mode::empty()) {
492 Ok(d) => d,
493 Err(_) => return result,
494 };
495
496 for item in dir.iter() {
497 if let Ok(entry) = item {
498 if let Ok(name) = entry.file_name().to_str() {
499 if name == "." || name == ".." { continue; }
500 let mut newpath = dirname.clone();
501 newpath.push(name);
502
503 if let Ok(stat) = nix::sys::stat::fstatat(libc::AT_FDCWD, &newpath, AtFlags::empty()) {
504 if (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR {
505 newpath.push("");
506 if let Some(newpath) = newpath.to_str() {
507 result.push(newpath.to_owned());
508 }
509 continue;
510 }
511 }
512 if let Some(newpath) = newpath.to_str() {
513 result.push(newpath.to_owned());
514 }
515
516 }
517 }
518 }
519
520 result
521}
443f3743
DM
522
523/// Scan directory for matching file names.
524///
525/// Scan through all directory entries and call `callback()` function
526/// if the entry name matches the regular expression. This function
527/// used unix `openat()`, so you can pass absolute or relative file
528/// names. This function simply skips non-UTF8 encoded names.
529pub fn scandir<P, F>(
530 dirfd: RawFd,
121f18ef 531 path: &P,
443f3743 532 regex: &regex::Regex,
cce1676a 533 mut callback: F
443f3743 534) -> Result<(), Error>
cce1676a 535 where F: FnMut(RawFd, &str, nix::dir::Type) -> Result<(), Error>,
121f18ef 536 P: ?Sized + nix::NixPath,
443f3743 537{
121f18ef 538 for entry in self::fs::scan_subdir(dirfd, path, regex)? {
443f3743
DM
539 let entry = entry?;
540 let file_type = match entry.file_type() {
541 Some(file_type) => file_type,
542 None => bail!("unable to detect file type"),
543 };
443f3743 544
121f18ef 545 callback(entry.parent_fd(), unsafe { entry.file_name_utf8_unchecked() }, file_type)?;
443f3743
DM
546 }
547 Ok(())
548}
7e13b2d6
DM
549
550pub fn get_hardware_address() -> Result<String, Error> {
551
1631c54f 552 static FILENAME: &str = "/etc/ssh/ssh_host_rsa_key.pub";
7e13b2d6 553
1631c54f 554 let contents = file_get_contents(FILENAME)?;
7e13b2d6
DM
555 let digest = md5::compute(contents);
556
557 Ok(format!("{:0x}", digest))
558}
22968600
DM
559
560pub fn digest_to_hex(digest: &[u8]) -> String {
561
562 const HEX_CHARS: &'static [u8; 16] = b"0123456789abcdef";
563
564 let mut buf = Vec::<u8>::with_capacity(digest.len()*2);
565
566 for i in 0..digest.len() {
567 buf.push(HEX_CHARS[(digest[i] >> 4) as usize]);
568 buf.push(HEX_CHARS[(digest[i] & 0xf) as usize]);
569 }
570
571 unsafe { String::from_utf8_unchecked(buf) }
572}
573
af2fddea
DM
574pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> {
575 if digest1 != digest2 {
576 bail!("detected modified configuration - file changed by other user? Try again.");
577 }
578 Ok(())
579}
b9903d63
DM
580
581/// Extract authentication cookie from cookie header.
582/// We assume cookie_name is already url encoded.
583pub fn extract_auth_cookie(cookie: &str, cookie_name: &str) -> Option<String> {
584
585 for pair in cookie.split(';') {
586
587 let (name, value) = match pair.find('=') {
588 Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()),
589 None => return None, // Cookie format error
590 };
591
592 if name == cookie_name {
593 use url::percent_encoding::percent_decode;
594 if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() {
595 return Some(value.into());
596 } else {
597 return None; // Cookie format error
598 }
599 }
600 }
601
602 None
603}
af53186e
DM
604
605pub fn join(data: &Vec<String>, sep: char) -> String {
606
607 let mut list = String::new();
608
609 for item in data {
610 if list.len() != 0 { list.push(sep); }
611 list.push_str(item);
612 }
613
614 list
615}
ff7049d4
WB
616
617pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> {
618 use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
619 let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?)
620 .ok_or_else(|| format_err!("unhandled file flags"))?; // nix crate is stupid this way...
621 flags.set(FdFlag::FD_CLOEXEC, on);
622 fcntl(fd, F_SETFD(flags))?;
623 Ok(())
624}
9136f857
DM
625
626
627static mut SHUTDOWN_REQUESTED: bool = false;
628
629pub fn request_shutdown() {
630 unsafe { SHUTDOWN_REQUESTED = true; }
7a630df7 631 crate::server::server_shutdown();
9136f857
DM
632}
633
634#[inline(always)]
635pub fn shutdown_requested() -> bool {
636 unsafe { SHUTDOWN_REQUESTED }
637}
92da93b2
DM
638
639pub fn fail_on_shutdown() -> Result<(), Error> {
640 if shutdown_requested() {
641 bail!("Server shutdown requested - aborting task");
642 }
643 Ok(())
644}
d96bb7f1
WB
645
646/// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
647/// `RawFd` is required without the corresponding handler object (such as when only the file
648/// descriptor number is required in a closure which may be dropped instead of being executed).
649pub struct Fd(pub RawFd);
650
651impl Drop for Fd {
652 fn drop(&mut self) {
653 if self.0 != -1 {
654 unsafe {
655 libc::close(self.0);
656 }
657 }
658 }
659}
660
661impl AsRawFd for Fd {
662 fn as_raw_fd(&self) -> RawFd {
663 self.0
664 }
665}
666
667impl IntoRawFd for Fd {
668 fn into_raw_fd(mut self) -> RawFd {
669 let fd = self.0;
670 self.0 = -1;
671 fd
672 }
673}
674
675impl FromRawFd for Fd {
676 unsafe fn from_raw_fd(fd: RawFd) -> Self {
677 Self(fd)
678 }
679}
efd1536e
WB
680
681// wrap nix::unistd::pipe2 + O_CLOEXEC into something returning guarded file descriptors
682pub fn pipe() -> Result<(Fd, Fd), Error> {
683 let (pin, pout) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?;
684 Ok((Fd(pin), Fd(pout)))
685}