Files
kinect/attach/linux/src/vhci_lifecycle.cpp
T
2026-11-25 05:09:31 -05:00

71 lines
2.1 KiB
C++

#include "attach_linux/vhci_lifecycle.h"
#include <sys/wait.h>
#include <array>
#include <cstdio>
#include <regex>
namespace attach::linux_attach {
namespace {
CommandResult run_shell(const std::string& command) {
std::string output;
FILE* pipe = ::popen((command + " 2>&1").c_str(), "r");
if (!pipe) {
return CommandResult{false, -1, "failed to spawn: " + command};
}
std::array<char, 4096> buffer{};
std::size_t read_bytes = 0;
while ((read_bytes = std::fread(buffer.data(), 1, buffer.size(), pipe)) > 0) {
output.append(buffer.data(), read_bytes);
}
const int status = ::pclose(pipe);
const int exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
return CommandResult{exit_code == 0, exit_code, output};
}
std::string shell_quote(const std::string& value) {
std::string quoted = "'";
for (const char c : value) {
quoted += (c == '\'') ? "'\\''" : std::string(1, c);
}
quoted += "'";
return quoted;
}
} // namespace
CommandResult usbip_attach(const std::string& host, uint16_t port, const std::string& busid) {
const std::string remote = host + ":" + std::to_string(port);
return run_shell("usbip attach -r " + shell_quote(remote) + " -b " + shell_quote(busid));
}
CommandResult usbip_detach(int vhci_port) {
return run_shell("usbip detach -p " + std::to_string(vhci_port));
}
CommandResult usbip_list_ports() {
return run_shell("usbip port");
}
CommandResult modprobe_vhci() {
return run_shell("modprobe vhci-hcd");
}
std::optional<int> parse_attached_port(const std::string& usbip_attach_output) {
// The usbip(8) client prints "succeeded" lines without a port number on
// most builds and relies on a follow-up `usbip port` listing to discover
// which vhci port it landed on; some builds instead print "...port N".
// Try the direct form first, else return nullopt so the caller falls back
// to `usbip_list_ports()`.
static const std::regex port_pattern(R"(port\s+(\d+))", std::regex::icase);
std::smatch match;
if (std::regex_search(usbip_attach_output, match, port_pattern)) {
return std::stoi(match[1].str());
}
return std::nullopt;
}
} // namespace attach::linux_attach