]> git.proxmox.com Git - proxmox-backup.git/blob - proxmox-rest-server/src/lib.rs
move src/server/environment.rs to proxmox-rest-server crate
[proxmox-backup.git] / proxmox-rest-server / src / lib.rs
1 use std::os::unix::io::RawFd;
2
3 use anyhow::{bail, format_err, Error};
4
5 use proxmox::tools::fd::Fd;
6
7 pub mod daemon;
8
9 mod environment;
10 pub use environment::*;
11
12 mod state;
13 pub use state::*;
14
15 mod command_socket;
16 pub use command_socket::*;
17
18 mod file_logger;
19 pub use file_logger::{FileLogger, FileLogOptions};
20
21 mod api_config;
22 pub use api_config::ApiConfig;
23
24 pub enum AuthError {
25 Generic(Error),
26 NoData,
27 }
28
29 impl From<Error> for AuthError {
30 fn from(err: Error) -> Self {
31 AuthError::Generic(err)
32 }
33 }
34
35 pub trait ApiAuth {
36 fn check_auth(
37 &self,
38 headers: &http::HeaderMap,
39 method: &hyper::Method,
40 ) -> Result<String, AuthError>;
41 }
42
43 static mut SHUTDOWN_REQUESTED: bool = false;
44
45 pub fn request_shutdown() {
46 unsafe {
47 SHUTDOWN_REQUESTED = true;
48 }
49 crate::server_shutdown();
50 }
51
52 #[inline(always)]
53 pub fn shutdown_requested() -> bool {
54 unsafe { SHUTDOWN_REQUESTED }
55 }
56
57 pub fn fail_on_shutdown() -> Result<(), Error> {
58 if shutdown_requested() {
59 bail!("Server shutdown requested - aborting task");
60 }
61 Ok(())
62 }
63
64 /// Helper to set/clear the FD_CLOEXEC flag on file descriptors
65 pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> {
66 use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD};
67 let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?)
68 .ok_or_else(|| format_err!("unhandled file flags"))?; // nix crate is stupid this way...
69 flags.set(FdFlag::FD_CLOEXEC, on);
70 fcntl(fd, F_SETFD(flags))?;
71 Ok(())
72 }
73
74 /// safe wrapper for `nix::sys::socket::socketpair` defaulting to `O_CLOEXEC` and guarding the file
75 /// descriptors.
76 pub fn socketpair() -> Result<(Fd, Fd), Error> {
77 use nix::sys::socket;
78 let (pa, pb) = socket::socketpair(
79 socket::AddressFamily::Unix,
80 socket::SockType::Stream,
81 None,
82 socket::SockFlag::SOCK_CLOEXEC,
83 )?;
84 Ok((Fd(pa), Fd(pb)))
85 }
86