net.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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(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->sock != -1)
  31. konf_client_disconnect(client);
  32. lub_string_free(client->path);
  33. free(client);
  34. }
  35. int konf_client_connect(konf_client_t *client)
  36. {
  37. struct sockaddr_un raddr;
  38. if (client->sock >= 0)
  39. return client->sock;
  40. if ((client->sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  41. return client->sock;
  42. raddr.sun_family = AF_UNIX;
  43. strncpy(raddr.sun_path, client->path, UNIX_PATH_MAX);
  44. raddr.sun_path[UNIX_PATH_MAX - 1] = '\0';
  45. if (connect(client->sock, (struct sockaddr *)&raddr, sizeof(raddr))) {
  46. close(client->sock);
  47. client->sock = -1;
  48. }
  49. return client->sock;
  50. }
  51. void konf_client_disconnect(konf_client_t *client)
  52. {
  53. if (client->sock >= 0) {
  54. close(client->sock);
  55. client->sock = -1;
  56. }
  57. }
  58. int konf_client_reconnect(konf_client_t *client)
  59. {
  60. konf_client_disconnect(client);
  61. return konf_client_connect(client);
  62. }
  63. int konf_client_send(konf_client_t *client, char *command)
  64. {
  65. if (client->sock < 0)
  66. return client->sock;
  67. return send(client->sock, command, strlen(command) + 1, MSG_NOSIGNAL);
  68. }
  69. int konf_client__get_sock(konf_client_t *client)
  70. {
  71. return client->sock;
  72. }