xs_unix_socket.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
  2. #ifndef _XS_UNIX_SOCKET_H
  3. #define _XS_UNIX_SOCKET_H
  4. int xs_unix_socket_server(const char *path, const char *grp);
  5. int xs_unix_socket_connect(const char *path);
  6. #ifdef XS_IMPLEMENTATION
  7. #include <sys/stat.h>
  8. #include <sys/un.h>
  9. #include <grp.h>
  10. int xs_unix_socket_server(const char *path, const char *grp)
  11. /* opens a unix-type server socket */
  12. {
  13. int rs = -1;
  14. if ((rs = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
  15. struct sockaddr_un su = {0};
  16. mode_t mode = 0666;
  17. su.sun_family = AF_UNIX;
  18. strncpy(su.sun_path, path, sizeof(su.sun_path));
  19. unlink(path);
  20. if (bind(rs, (struct sockaddr *)&su, sizeof(su)) == -1) {
  21. close(rs);
  22. return -1;
  23. }
  24. listen(rs, SOMAXCONN);
  25. if (grp != NULL) {
  26. struct group *g = NULL;
  27. /* if there is a group name, get its gid_t */
  28. g = getgrnam(grp);
  29. if (g != NULL && chown(path, -1, g->gr_gid) != -1)
  30. mode = 0660;
  31. }
  32. chmod(path, mode);
  33. }
  34. return rs;
  35. }
  36. int xs_unix_socket_connect(const char *path)
  37. /* connects to a unix-type socket */
  38. {
  39. int d = -1;
  40. if ((d = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
  41. struct sockaddr_un su = {0};
  42. su.sun_family = AF_UNIX;
  43. strncpy(su.sun_path, path, sizeof(su.sun_path));
  44. if (connect(d, (struct sockaddr *)&su, sizeof(su)) == -1) {
  45. close(d);
  46. d = -1;
  47. }
  48. }
  49. return d;
  50. }
  51. #endif /* XS_IMPLEMENTATION */
  52. #endif /* _XS_UNIX_SOCKET_H */