Use 64-bit capabilities if available

This will fix the following warning in dmesg:

    capability: warning: `clickhouse-serv' uses 32-bit capabilities (legacy support in use)

P.S. I'm not even sure that the fallback code is useful, since
_LINUX_CAPABILITY_VERSION_3 had been added long time ago, in Linux
2.6.26 (Released 13 July 2008)

Signed-off-by: Azat Khuzhin <a.khuzhin@semrush.com>
This commit is contained in:
Azat Khuzhin 2024-03-04 16:18:53 +01:00
parent f07f438fe6
commit 081ed8de2a

View File

@ -5,6 +5,8 @@
#include <syscall.h>
#include <unistd.h>
#include <linux/capability.h>
#include <cstdint>
#include <base/types.h>
#include <Common/Exception.h>
@ -16,25 +18,48 @@ namespace ErrorCodes
extern const int NETLINK_ERROR;
}
static __user_cap_data_struct getCapabilities()
struct Capabilities
{
UInt64 effective;
UInt64 permitted;
UInt64 inheritable;
};
static Capabilities getCapabilities()
{
/// See man getcap.
__user_cap_header_struct request{};
request.version = _LINUX_CAPABILITY_VERSION_1; /// It's enough to check just single CAP_NET_ADMIN capability we are interested.
request.version = _LINUX_CAPABILITY_VERSION_3;
request.pid = getpid();
__user_cap_data_struct response{};
Capabilities ret{};
__user_cap_data_struct response[2] = {};
/// Avoid dependency on 'libcap'.
if (0 != syscall(SYS_capget, &request, &response))
throw ErrnoException(ErrorCodes::NETLINK_ERROR, "Cannot do 'capget' syscall");
if (0 == syscall(SYS_capget, &request, response))
{
ret.effective = static_cast<UInt64>(response[1].effective) << 32 | response[0].effective;
ret.permitted = static_cast<UInt64>(response[1].permitted) << 32 | response[0].permitted;
ret.inheritable = static_cast<UInt64>(response[1].inheritable) << 32 | response[0].inheritable;
return ret;
}
return response;
/// Does not supports V3, fallback to V1.
/// It's enough to check just single CAP_NET_ADMIN capability we are interested.
if (errno == EINVAL && 0 == syscall(SYS_capget, &request, response))
{
ret.effective = response[0].effective;
ret.permitted = response[0].permitted;
ret.inheritable = response[0].inheritable;
return ret;
}
throw ErrnoException(ErrorCodes::NETLINK_ERROR, "Cannot do 'capget' syscall");
}
bool hasLinuxCapability(int cap)
{
static __user_cap_data_struct capabilities = getCapabilities();
static Capabilities capabilities = getCapabilities();
return (1 << cap) & capabilities.effective;
}