From 972c3dc5d43a114ae59386d4edfdfb8ce0f3793e Mon Sep 17 00:00:00 2001 From: default Date: Mon, 5 Aug 2024 06:01:21 +0200 Subject: Added support for listening on unix sockets. --- xs_unix_socket.h | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 xs_unix_socket.h (limited to 'xs_unix_socket.h') diff --git a/xs_unix_socket.h b/xs_unix_socket.h new file mode 100644 index 0000000..5b64282 --- /dev/null +++ b/xs_unix_socket.h @@ -0,0 +1,78 @@ +/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */ + +#ifndef _XS_UNIX_SOCKET_H + +#define _XS_UNIX_SOCKET_H + + int xs_unix_socket_server(const char *path, const char *grp); + int xs_unix_socket_connect(const char *path); + + +#ifdef XS_IMPLEMENTATION + +#include +#include +#include + +int xs_unix_socket_server(const char *path, const char *grp) +/* opens a unix-type server socket */ +{ + int rs = -1; + + if ((rs = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) { + struct sockaddr_un sun = {0}; + mode_t mode = 0666; + + sun.sun_family = AF_UNIX; + strncpy(sun.sun_path, path, sizeof(sun.sun_path)); + + unlink(path); + + if (bind(rs, (struct sockaddr *)&sun, sizeof(sun)) == -1) { + close(rs); + return -1; + } + + listen(rs, SOMAXCONN); + + if (grp != NULL) { + struct group *g = NULL; + + /* if there is a group name, get its gid_t */ + g = getgrnam(grp); + + if (g != NULL && chown(path, -1, g->gr_gid) != -1) + mode = 0660; + } + + chmod(path, mode); + } + + return rs; +} + + +int xs_unix_socket_connect(const char *path) +/* connects to a unix-type socket */ +{ + int d = -1; + + if ((d = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) { + struct sockaddr_un sun = {0}; + + sun.sun_family = AF_UNIX; + strncpy(sun.sun_path, path, sizeof(sun.sun_path)); + + if (connect(d, (struct sockaddr *)&sun, sizeof(sun)) == -1) { + close(d); + d = -1; + } + } + + return d; +} + + +#endif /* XS_IMPLEMENTATION */ + +#endif /* _XS_UNIX_SOCKET_H */ -- cgit v1.2.3