2024-04-20 19:50:07 +02:00
|
|
|
#include "SdDaemon.hpp"
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <unistd.h>
|
2024-05-08 00:13:58 +02:00
|
|
|
#include <errno.h>
|
2024-04-20 19:50:07 +02:00
|
|
|
#include <sys/socket.h>
|
|
|
|
#include <sys/un.h>
|
2024-05-16 00:01:48 +02:00
|
|
|
#include <string.h>
|
2024-08-10 22:09:12 +02:00
|
|
|
#include <cstring>
|
2024-04-20 19:50:07 +02:00
|
|
|
|
|
|
|
namespace Systemd {
|
|
|
|
int SdBooted(void) {
|
|
|
|
if (!faccessat(AT_FDCWD, "/run/systemd/system/", F_OK, AT_SYMLINK_NOFOLLOW))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (errno == ENOENT)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return -errno;
|
|
|
|
}
|
|
|
|
|
|
|
|
int SdNotify(int unsetEnvironment, const char* state) {
|
2024-06-09 09:43:39 +02:00
|
|
|
int fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
|
|
|
|
if (fd < 0)
|
2024-04-20 19:50:07 +02:00
|
|
|
return -errno;
|
|
|
|
|
|
|
|
constexpr char envVar[] = "NOTIFY_SOCKET";
|
|
|
|
|
|
|
|
auto cleanup = [unsetEnvironment, envVar](int* fd) {
|
|
|
|
if (unsetEnvironment)
|
|
|
|
unsetenv(envVar);
|
|
|
|
close(*fd);
|
|
|
|
};
|
|
|
|
std::unique_ptr<int, decltype(cleanup)> fdCleaup(&fd, cleanup);
|
|
|
|
|
|
|
|
const char* addr = getenv(envVar);
|
|
|
|
if (!addr)
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
// address length must be at most this; see man 7 unix
|
|
|
|
size_t addrLen = strnlen(addr, 107);
|
|
|
|
|
|
|
|
struct sockaddr_un unixAddr;
|
|
|
|
unixAddr.sun_family = AF_UNIX;
|
|
|
|
strncpy(unixAddr.sun_path, addr, addrLen);
|
|
|
|
if (unixAddr.sun_path[0] == '@')
|
|
|
|
unixAddr.sun_path[0] = '\0';
|
|
|
|
|
2024-06-09 09:43:39 +02:00
|
|
|
if (connect(fd, (const sockaddr*)&unixAddr, sizeof(struct sockaddr_un)) < 0)
|
|
|
|
return -errno;
|
2024-04-20 19:50:07 +02:00
|
|
|
|
|
|
|
// arbitrary value which seems to be enough for s-d messages
|
2024-06-09 09:43:39 +02:00
|
|
|
ssize_t stateLen = strnlen(state, 128);
|
|
|
|
if (write(fd, state, stateLen) == stateLen)
|
2024-04-20 19:50:07 +02:00
|
|
|
return 1;
|
|
|
|
|
|
|
|
return -errno;
|
|
|
|
}
|
|
|
|
}
|