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