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
,
18 pub use pbs_tools
::json
;
19 pub use pbs_tools
::nom
;
20 pub use pbs_tools
::{run_command, command_output, command_output_as_string}
;
21 pub use pbs_tools
::process_locker
::{
22 ProcessLocker
, ProcessLockExclusiveGuard
, ProcessLockSharedGuard
33 pub use memcom
::Memcom
;
42 pub mod parallel_handler
;
43 pub use parallel_handler
::ParallelHandler
;
46 pub use file_logger
::{FileLogger, FileLogOptions}
;
48 pub use pbs_tools
::broadcast_future
::{BroadcastData, BroadcastFuture}
;
49 pub use pbs_tools
::ops
::ControlFlow
;
51 /// Shortcut for md5 sums.
52 pub fn md5sum(data
: &[u8]) -> Result
<DigestBytes
, Error
> {
53 hash(MessageDigest
::md5(), data
).map_err(Error
::from
)
56 pub fn get_hardware_address() -> Result
<String
, Error
> {
57 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
59 let contents
= proxmox
::tools
::fs
::file_get_contents(FILENAME
)
60 .map_err(|e
| format_err
!("Error getting host key - {}", e
))?
;
61 let digest
= md5sum(&contents
)
62 .map_err(|e
| format_err
!("Error digesting host key - {}", e
))?
;
64 Ok(proxmox
::tools
::bin_to_hex(&digest
).to_uppercase())
67 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
68 if digest1
!= digest2
{
69 bail
!("detected modified configuration - file changed by other user? Try again.");
74 /// Extract a specific cookie from cookie header.
75 /// We assume cookie_name is already url encoded.
76 pub fn extract_cookie(cookie
: &str, cookie_name
: &str) -> Option
<String
> {
77 for pair
in cookie
.split('
;'
) {
78 let (name
, value
) = match pair
.find('
='
) {
79 Some(i
) => (pair
[..i
].trim(), pair
[(i
+ 1)..].trim()),
80 None
=> return None
, // Cookie format error
83 if name
== cookie_name
{
84 use percent_encoding
::percent_decode
;
85 if let Ok(value
) = percent_decode(value
.as_bytes()).decode_utf8() {
86 return Some(value
.into());
88 return None
; // Cookie format error
96 /// Detect modified configuration files
98 /// This function fails with a reasonable error message if checksums do not match.
99 pub fn detect_modified_configuration_file(digest1
: &[u8;32], digest2
: &[u8;32]) -> Result
<(), Error
> {
100 if digest1
!= digest2
{
101 bail
!("detected modified configuration - file changed by other user? Try again.");
106 /// normalize uri path
108 /// Do not allow ".", "..", or hidden files ".XXXX"
109 /// Also remove empty path components
110 pub fn normalize_uri_path(path
: &str) -> Result
<(String
, Vec
<&str>), Error
> {
111 let items
= path
.split('
/'
);
113 let mut path
= String
::new();
114 let mut components
= vec
![];
120 if name
.starts_with('
.'
) {
121 bail
!("Path contains illegal components.");
125 components
.push(name
);
128 Ok((path
, components
))
131 pub fn fd_change_cloexec(fd
: RawFd
, on
: bool
) -> Result
<(), Error
> {
132 use nix
::fcntl
::{fcntl, FdFlag, F_GETFD, F_SETFD}
;
133 let mut flags
= FdFlag
::from_bits(fcntl(fd
, F_GETFD
)?
)
134 .ok_or_else(|| format_err
!("unhandled file flags"))?
; // nix crate is stupid this way...
135 flags
.set(FdFlag
::FD_CLOEXEC
, on
);
136 fcntl(fd
, F_SETFD(flags
))?
;
140 static mut SHUTDOWN_REQUESTED
: bool
= false;
142 pub fn request_shutdown() {
144 SHUTDOWN_REQUESTED
= true;
146 crate::server
::server_shutdown();
150 pub fn shutdown_requested() -> bool
{
151 unsafe { SHUTDOWN_REQUESTED }
154 pub fn fail_on_shutdown() -> Result
<(), Error
> {
155 if shutdown_requested() {
156 bail
!("Server shutdown requested - aborting task");
161 /// safe wrapper for `nix::sys::socket::socketpair` defaulting to `O_CLOEXEC` and guarding the file
163 pub fn socketpair() -> Result
<(Fd
, Fd
), Error
> {
164 use nix
::sys
::socket
;
165 let (pa
, pb
) = socket
::socketpair(
166 socket
::AddressFamily
::Unix
,
167 socket
::SockType
::Stream
,
169 socket
::SockFlag
::SOCK_CLOEXEC
,
175 /// An easy way to convert types to Any
177 /// Mostly useful to downcast trait objects (see RpcEnvironment).
179 fn as_any(&self) -> &dyn Any
;
182 impl<T
: Any
> AsAny
for T
{
183 fn as_any(&self) -> &dyn Any
{
188 /// The default 2 hours are far too long for PBS
189 pub const PROXMOX_BACKUP_TCP_KEEPALIVE_TIME
: u32 = 120;
190 pub const DEFAULT_USER_AGENT_STRING
: &'
static str = "proxmox-backup-client/1.0";
192 /// Returns a new instance of `SimpleHttp` configured for PBS usage.
193 pub fn pbs_simple_http(proxy_config
: Option
<ProxyConfig
>) -> SimpleHttp
{
194 let options
= SimpleHttpOptions
{
196 user_agent
: Some(DEFAULT_USER_AGENT_STRING
.to_string()),
197 tcp_keepalive
: Some(PROXMOX_BACKUP_TCP_KEEPALIVE_TIME
),
201 SimpleHttp
::with_options(options
)
204 pub fn setup_safe_path_env() {
205 std
::env
::set_var("PATH", "/sbin:/bin:/usr/sbin:/usr/bin");
206 // Make %ENV safer - as suggested by https://perldoc.perl.org/perlsec.html
207 for name
in &["IFS", "CDPATH", "ENV", "BASH_ENV"] {
208 std
::env
::remove_var(name
);