1 //! Tools and utilities
3 //! This is a collection of small and useful tools.
5 use std
::os
::unix
::io
::RawFd
;
7 use anyhow
::{bail, format_err, Error}
;
8 use openssl
::hash
::{hash, DigestBytes, MessageDigest}
;
10 pub use proxmox
::tools
::fd
::Fd
;
14 client
::SimpleHttpOptions
,
31 pub mod parallel_handler
;
32 pub use parallel_handler
::ParallelHandler
;
34 /// Shortcut for md5 sums.
35 pub fn md5sum(data
: &[u8]) -> Result
<DigestBytes
, Error
> {
36 hash(MessageDigest
::md5(), data
).map_err(Error
::from
)
39 pub fn get_hardware_address() -> Result
<String
, Error
> {
40 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
42 let contents
= proxmox
::tools
::fs
::file_get_contents(FILENAME
)
43 .map_err(|e
| format_err
!("Error getting host key - {}", e
))?
;
44 let digest
= md5sum(&contents
)
45 .map_err(|e
| format_err
!("Error digesting host key - {}", e
))?
;
47 Ok(proxmox
::tools
::bin_to_hex(&digest
).to_uppercase())
50 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
51 if digest1
!= digest2
{
52 bail
!("detected modified configuration - file changed by other user? Try again.");
57 /// Extract a specific cookie from cookie header.
58 /// We assume cookie_name is already url encoded.
59 pub fn extract_cookie(cookie
: &str, cookie_name
: &str) -> Option
<String
> {
60 for pair
in cookie
.split('
;'
) {
61 let (name
, value
) = match pair
.find('
='
) {
62 Some(i
) => (pair
[..i
].trim(), pair
[(i
+ 1)..].trim()),
63 None
=> return None
, // Cookie format error
66 if name
== cookie_name
{
67 use percent_encoding
::percent_decode
;
68 if let Ok(value
) = percent_decode(value
.as_bytes()).decode_utf8() {
69 return Some(value
.into());
71 return None
; // Cookie format error
79 /// Detect modified configuration files
81 /// This function fails with a reasonable error message if checksums do not match.
82 pub fn detect_modified_configuration_file(digest1
: &[u8;32], digest2
: &[u8;32]) -> Result
<(), Error
> {
83 if digest1
!= digest2
{
84 bail
!("detected modified configuration - file changed by other user? Try again.");
89 /// normalize uri path
91 /// Do not allow ".", "..", or hidden files ".XXXX"
92 /// Also remove empty path components
93 pub fn normalize_uri_path(path
: &str) -> Result
<(String
, Vec
<&str>), Error
> {
94 let items
= path
.split('
/'
);
96 let mut path
= String
::new();
97 let mut components
= vec
![];
103 if name
.starts_with('
.'
) {
104 bail
!("Path contains illegal components.");
108 components
.push(name
);
111 Ok((path
, components
))
114 pub fn fd_change_cloexec(fd
: RawFd
, on
: bool
) -> Result
<(), Error
> {
115 use nix
::fcntl
::{fcntl, FdFlag, F_GETFD, F_SETFD}
;
116 let mut flags
= FdFlag
::from_bits(fcntl(fd
, F_GETFD
)?
)
117 .ok_or_else(|| format_err
!("unhandled file flags"))?
; // nix crate is stupid this way...
118 flags
.set(FdFlag
::FD_CLOEXEC
, on
);
119 fcntl(fd
, F_SETFD(flags
))?
;
123 /// safe wrapper for `nix::sys::socket::socketpair` defaulting to `O_CLOEXEC` and guarding the file
125 pub fn socketpair() -> Result
<(Fd
, Fd
), Error
> {
126 use nix
::sys
::socket
;
127 let (pa
, pb
) = socket
::socketpair(
128 socket
::AddressFamily
::Unix
,
129 socket
::SockType
::Stream
,
131 socket
::SockFlag
::SOCK_CLOEXEC
,
137 /// An easy way to convert types to Any
139 /// Mostly useful to downcast trait objects (see RpcEnvironment).
141 fn as_any(&self) -> &dyn Any
;
144 impl<T
: Any
> AsAny
for T
{
145 fn as_any(&self) -> &dyn Any
{
150 /// The default 2 hours are far too long for PBS
151 pub const PROXMOX_BACKUP_TCP_KEEPALIVE_TIME
: u32 = 120;
152 pub const DEFAULT_USER_AGENT_STRING
: &'
static str = "proxmox-backup-client/1.0";
154 /// Returns a new instance of `SimpleHttp` configured for PBS usage.
155 pub fn pbs_simple_http(proxy_config
: Option
<ProxyConfig
>) -> SimpleHttp
{
156 let options
= SimpleHttpOptions
{
158 user_agent
: Some(DEFAULT_USER_AGENT_STRING
.to_string()),
159 tcp_keepalive
: Some(PROXMOX_BACKUP_TCP_KEEPALIVE_TIME
),
163 SimpleHttp
::with_options(options
)
166 pub fn setup_safe_path_env() {
167 std
::env
::set_var("PATH", "/sbin:/bin:/usr/sbin:/usr/bin");
168 // Make %ENV safer - as suggested by https://perldoc.perl.org/perlsec.html
169 for name
in &["IFS", "CDPATH", "ENV", "BASH_ENV"] {
170 std
::env
::remove_var(name
);