ktp.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include <unistd.h>
  6. #include <errno.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. #include <sys/socket.h>
  11. #include <sys/un.h>
  12. #include <faux/str.h>
  13. #include <klish/ktp.h>
  14. #include "private.h"
  15. int ktp_connect(const char *sun_path)
  16. {
  17. int sock = -1;
  18. int opt = 1;
  19. struct sockaddr_un laddr = {};
  20. assert(sun_path);
  21. if (!sun_path)
  22. return -1;
  23. // Create socket
  24. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
  25. return -1;
  26. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
  27. close(sock);
  28. return -1;
  29. }
  30. laddr.sun_family = AF_UNIX;
  31. strncpy(laddr.sun_path, sun_path, USOCK_PATH_MAX);
  32. laddr.sun_path[USOCK_PATH_MAX - 1] = '\0';
  33. // Connect to server
  34. if (connect(sock, (struct sockaddr *)&laddr, sizeof(laddr))) {
  35. close(sock);
  36. return -1;
  37. }
  38. return sock;
  39. }
  40. void ktp_disconnect(int fd)
  41. {
  42. if (fd < 0)
  43. return;
  44. close(fd);
  45. }
  46. int ktp_accept(int listen_sock)
  47. {
  48. int new_conn = -1;
  49. new_conn = accept(listen_sock, NULL, NULL);
  50. return new_conn;
  51. }