diff options
author | default <nobody@localhost> | 2024-08-05 06:01:21 +0200 |
---|---|---|
committer | default <nobody@localhost> | 2024-08-05 06:01:21 +0200 |
commit | 972c3dc5d43a114ae59386d4edfdfb8ce0f3793e (patch) | |
tree | 2568b6190dc0ca34478ccabc1191e504d1e8cfcf /xs_unix_socket.h | |
parent | e9b108a6e0f09d74ee605f1a854ecbdc12a65c92 (diff) |
Added support for listening on unix sockets.
Diffstat (limited to 'xs_unix_socket.h')
-rw-r--r-- | xs_unix_socket.h | 78 |
1 files changed, 78 insertions, 0 deletions
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 <sys/stat.h> +#include <sys/un.h> +#include <grp.h> + +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 */ |