net.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. #include <errno.h>
  7. #include <assert.h>
  8. #include <sys/socket.h>
  9. #include <string.h>
  10. #include <sys/un.h>
  11. #include "clish/private.h"
  12. #include "lub/string.h"
  13. #include "private.h"
  14. #ifndef UNIX_PATH_MAX
  15. #define UNIX_PATH_MAX 108
  16. #endif
  17. konf_client_t *konf_client_new(const char *path)
  18. {
  19. konf_client_t *client;
  20. if (!path)
  21. return NULL;
  22. if (!(client = malloc(sizeof(*client))))
  23. return NULL;
  24. client->sock = -1; /* socket is not created yet */
  25. client->path = lub_string_dup(path);
  26. return client;
  27. }
  28. void konf_client_free(konf_client_t *client)
  29. {
  30. if (!client)
  31. return;
  32. if (client->sock != -1)
  33. konf_client_disconnect(client);
  34. lub_string_free(client->path);
  35. free(client);
  36. }
  37. int konf_client_connect(konf_client_t *client)
  38. {
  39. struct sockaddr_un raddr;
  40. if (client->sock >= 0)
  41. return client->sock;
  42. if ((client->sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  43. return client->sock;
  44. raddr.sun_family = AF_UNIX;
  45. strncpy(raddr.sun_path, client->path, UNIX_PATH_MAX);
  46. raddr.sun_path[UNIX_PATH_MAX - 1] = '\0';
  47. if (connect(client->sock, (struct sockaddr *)&raddr, sizeof(raddr))) {
  48. close(client->sock);
  49. client->sock = -1;
  50. }
  51. return client->sock;
  52. }
  53. void konf_client_disconnect(konf_client_t *client)
  54. {
  55. if (client->sock >= 0) {
  56. close(client->sock);
  57. client->sock = -1;
  58. }
  59. }
  60. int konf_client_reconnect(konf_client_t *client)
  61. {
  62. konf_client_disconnect(client);
  63. return konf_client_connect(client);
  64. }
  65. int konf_client_send(konf_client_t *client, char *command)
  66. {
  67. if (client->sock < 0)
  68. return client->sock;
  69. return send(client->sock, command, strlen(command) + 1, MSG_NOSIGNAL);
  70. }
  71. int konf_client__get_sock(konf_client_t *client)
  72. {
  73. return client->sock;
  74. }