Skip to content

Commit 4610b1b

Browse files
committed
audiod-mon check for sudo on socket
1 parent 94a1c8c commit 4610b1b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

examples/audiod-mon.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,45 @@ static void disable_raw_mode() {
6666
}
6767

6868
// ── control socket helper ───────────────────────────────────────────
69+
70+
// Check whether the control socket is accessible. Returns true if
71+
// connect() succeeds (or the socket doesn't exist — nothing to fix).
72+
static bool can_access_socket(const std::string& socket_path) {
73+
struct stat st;
74+
if (stat(socket_path.c_str(), &st) != 0)
75+
return true; // socket doesn't exist yet; nothing we can do
76+
77+
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
78+
if (fd < 0) return false;
79+
80+
struct sockaddr_un addr;
81+
std::memset(&addr, 0, sizeof(addr));
82+
addr.sun_family = AF_UNIX;
83+
std::strncpy(addr.sun_path, socket_path.c_str(),
84+
sizeof(addr.sun_path) - 1);
85+
86+
bool ok = connect(fd, reinterpret_cast<struct sockaddr*>(&addr),
87+
sizeof(addr)) == 0;
88+
close(fd);
89+
return ok;
90+
}
91+
92+
// Re-exec ourselves under sudo, preserving all original arguments.
93+
static void reexec_with_sudo(int argc, char* argv[]) {
94+
// argv for execvp: "sudo" + original args + nullptr
95+
std::vector<const char*> args;
96+
args.push_back("sudo");
97+
for (int i = 0; i < argc; ++i)
98+
args.push_back(argv[i]);
99+
args.push_back(nullptr);
100+
101+
std::cerr << "Control socket requires elevated privileges, re-running with sudo…\n";
102+
execvp("sudo", const_cast<char* const*>(args.data()));
103+
// execvp only returns on failure
104+
std::cerr << "Failed to exec sudo: " << strerror(errno) << "\n";
105+
_exit(1);
106+
}
107+
69108
static std::string send_command(const std::string& socket_path,
70109
const std::string& cmd) {
71110
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
@@ -161,6 +200,12 @@ int main(int argc, char* argv[]) {
161200
}
162201
}
163202

203+
// ── check control socket permissions ────────────────────────────
204+
if (!can_access_socket(socket_path) && geteuid() != 0) {
205+
reexec_with_sudo(argc, argv);
206+
// does not return
207+
}
208+
164209
// ── open shared memory ──────────────────────────────────────────
165210
int fd = shm_open(shm_name.c_str(), O_RDONLY, 0);
166211
if (fd < 0) {

0 commit comments

Comments
 (0)