Skip to content
Repos

mologram

C++ 1.9 KB59 lines Opens in site

Directory Raw Download

#include "mologram/SocketUtil.hpp"

#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>

namespace mologram {

static bool fill(const std::string& path, sockaddr_un& a) {
  std::memset(&a, 0, sizeof(a));
  a.sun_family = AF_UNIX;
  if (path.size() >= sizeof(a.sun_path)) return false;
  std::memcpy(a.sun_path, path.c_str(), path.size() + 1);
  return true;
}

Fd SocketUtil::listenUnix(const std::string& path, std::string& err) {
  sockaddr_un a;
  if (!fill(path, a)) { err = "socket path too long for a unix socket"; return Fd(); }
  Fd fd(::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0));
  if (!fd.valid()) { err = std::string("socket: ") + std::strerror(errno); return Fd(); }
  mode_t old = ::umask(0177);
  int rc = ::bind(fd.get(), (sockaddr*)&a, sizeof(a));
  int e = errno;
  ::umask(old);
  if (rc != 0) { err = std::string("bind: ") + std::strerror(e); return Fd(); }
  ::chmod(path.c_str(), 0600);
  if (::listen(fd.get(), SOMAXCONN) != 0) { err = std::string("listen: ") + std::strerror(errno); return Fd(); }
  return fd;
}

Fd SocketUtil::connectUnix(const std::string& path, int& errnoOut) {
  sockaddr_un a;
  errnoOut = 0;
  if (!fill(path, a)) { errnoOut = ENAMETOOLONG; return Fd(); }
  Fd fd(::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0));
  if (!fd.valid()) { errnoOut = errno; return Fd(); }
  if (::connect(fd.get(), (sockaddr*)&a, sizeof(a)) != 0) { errnoOut = errno; return Fd(); }
  return fd;
}

bool SocketUtil::setNonBlocking(int fd) {
  int fl = ::fcntl(fd, F_GETFL, 0);
  return fl >= 0 && ::fcntl(fd, F_SETFL, fl | O_NONBLOCK) == 0;
}

bool SocketUtil::writeAll(int fd, const char* data, size_t len) {
  while (len > 0) {
    ssize_t n = ::send(fd, data, len, MSG_NOSIGNAL);
    if (n < 0) { if (errno == EINTR) continue; return false; }
    data += n; len -= (size_t)n;
  }
  return true;
}

} // namespace mologram
28.2ms