Skip to content

Commit

Permalink
Merge pull request #41 from hoytech/master
Browse files Browse the repository at this point in the history
Support listening on AF_UNIX sockets
  • Loading branch information
mattgodbolt authored Dec 16, 2016
2 parents 0beca0c + 1cd4ceb commit 306b460
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/main/c/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/un.h>

#include <memory>
#include <stdexcept>
Expand Down Expand Up @@ -237,6 +238,43 @@ bool Server::startListening(uint32_t hostAddr, int port) {
return true;
}

bool Server::startListeningUnix(const char* socketPath) {
struct sockaddr_un sock;

_listenSock = socket(AF_UNIX, SOCK_STREAM, 0);
if (_listenSock == -1) {
LS_ERROR(_logger, "Unable to create unix listen socket: " << getLastError());
return false;
}
if (!configureSocket(_listenSock)) {
return false;
}

memset(&sock, 0, sizeof(struct sockaddr_un));
sock.sun_family = AF_UNIX;
strncpy(sock.sun_path, socketPath, sizeof(sock.sun_path) - 1);

if (bind(_listenSock, reinterpret_cast<const sockaddr*>(&sock), sizeof(sock)) == -1) {
LS_ERROR(_logger, "Unable to bind unix socket (" << socketPath << "): " << getLastError());
return false;
}

if (listen(_listenSock, 5) == -1) {
LS_ERROR(_logger, "Unable to listen on unix socket: " << getLastError());
return false;
}

epoll_event event = { EPOLLIN, { this } };
if (epoll_ctl(_epollFd, EPOLL_CTL_ADD, _listenSock, &event) == -1) {
LS_ERROR(_logger, "Unable to add unix listen socket to epoll: " << getLastError());
return false;
}

LS_INFO(_logger, "Listening on unix socket: http://unix:" << socketPath);

return true;
}

void Server::handlePipe() {
uint64_t dummy;
while (::read(_eventFd, &dummy, sizeof(dummy)) != -1) {
Expand Down
4 changes: 4 additions & 0 deletions src/main/c/seasocks/Server.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ class Server : private ServerImpl {
// Returns true if all was ok.
bool startListening(int port);

// Starts listening on a unix domain socket.
// Returns true if all was ok.
bool startListeningUnix(const char* socketPath);

// Sets the path to server static content from.
void setStaticPath(const char* staticPath);

Expand Down

0 comments on commit 306b460

Please sign in to comment.