diff --git a/include/villas/api/server.hpp b/include/villas/api/server.hpp index 3b6c9c320..85bd4afc8 100644 --- a/include/villas/api/server.hpp +++ b/include/villas/api/server.hpp @@ -27,6 +27,8 @@ #include #include +#include +#include #include #include @@ -62,6 +64,8 @@ protected: void acceptNewSession(); void closeSession(sessions::Socket *s); + struct sockaddr_un getSocketAddress(); + public: Server(Api *a); ~Server(); diff --git a/lib/api/server.cpp b/lib/api/server.cpp index 5a743ed12..8f443a4a2 100644 --- a/lib/api/server.cpp +++ b/lib/api/server.cpp @@ -21,9 +21,8 @@ * along with this program. If not, see . *********************************************************************************/ -#include -#include #include +#include #include #include @@ -79,9 +78,36 @@ void Server::start() pfds.push_back(pfd); + struct sockaddr_un sun = getSocketAddress(); + + ret = bind(sd, (struct sockaddr *) &sun, sizeof(struct sockaddr_un)); + if (ret) + throw SystemError("Failed to bind API socket"); + + ret = listen(sd, 5); + if (ret) + throw SystemError("Failed to listen on API socket"); + + logger->info("Listening on UNIX socket: {}", sun.sun_path); + + state = STATE_STARTED; +} + +struct sockaddr_un Server::getSocketAddress() +{ struct sockaddr_un sun = { .sun_family = AF_UNIX }; - fs::path socketPath = PREFIX "/var/lib/villas"; + fs::path socketPath; + + if (getuid() == 0) { + socketPath = PREFIX "/var/lib/villas"; + } + else { + std::string homeDir = getenv("HOME"); + + socketPath = homeDir + "/.villas"; + } + if (!fs::exists(socketPath)) { logging.get("api")->info("Creating directory for API socket: {}", socketPath); fs::create_directories(socketPath); @@ -96,17 +122,7 @@ void Server::start() strncpy(sun.sun_path, socketPath.c_str(), sizeof(sun.sun_path) - 1); - ret = bind(sd, (struct sockaddr *) &sun, sizeof(struct sockaddr_un)); - if (ret) - throw SystemError("Failed to bind API socket"); - - ret = listen(sd, 5); - if (ret) - throw SystemError("Failed to listen on API socket"); - - logger->info("Listening on UNIX socket: {}", socketPath); - - state = STATE_STARTED; + return sun; } void Server::stop()