xs_unix_socket.h (1873B)
1 /* copyright (c) 2022 - 2025 grunfink et al. / MIT license */ 2 3 #ifndef _XS_UNIX_SOCKET_H 4 5 #define _XS_UNIX_SOCKET_H 6 7 int xs_unix_socket_server(const char *path, const char *grp); 8 int xs_unix_socket_connect(const char *path); 9 10 11 #ifdef XS_IMPLEMENTATION 12 13 #include <sys/stat.h> 14 #include <sys/un.h> 15 #include <grp.h> 16 17 int xs_unix_socket_server(const char *path, const char *grp) 18 /* opens a unix-type server socket */ 19 { 20 int rs = -1; 21 struct sockaddr_un su = {0}; 22 socklen_t plen = strlen(path); 23 24 if (plen >= sizeof(su.sun_path)) return -1; 25 26 if ((rs = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) { 27 mode_t mode = 0666; 28 29 su.sun_family = AF_UNIX; 30 memcpy(su.sun_path, path, plen + 1); 31 plen += offsetof(struct sockaddr_un, sun_path) + 1; 32 33 unlink(path); 34 35 if (bind(rs, (struct sockaddr *)&su, plen) == -1) { 36 close(rs); 37 return -1; 38 } 39 40 listen(rs, SOMAXCONN); 41 42 if (grp != NULL) { 43 struct group *g = NULL; 44 45 /* if there is a group name, get its gid_t */ 46 g = getgrnam(grp); 47 48 if (g != NULL && chown(path, -1, g->gr_gid) != -1) 49 mode = 0660; 50 } 51 52 chmod(path, mode); 53 } 54 55 return rs; 56 } 57 58 59 int xs_unix_socket_connect(const char *path) 60 /* connects to a unix-type socket */ 61 { 62 struct sockaddr_un su = {0}; 63 int d = -1; 64 65 socklen_t plen = strlen(path); 66 67 if (plen >= sizeof(su.sun_path)) return -1; 68 69 if ((d = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) { 70 su.sun_family = AF_UNIX; 71 memcpy(su.sun_path, path, plen + 1); 72 73 plen += offsetof(struct sockaddr_un, sun_path) + 1; 74 75 if (connect(d, (struct sockaddr *)&su, plen) == -1) { 76 close(d); 77 d = -1; 78 } 79 } 80 81 return d; 82 } 83 84 85 #endif /* XS_IMPLEMENTATION */ 86 87 #endif /* _XS_UNIX_SOCKET_H */