net.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * clish_config_callback.c
  3. *
  4. *
  5. * Callback hook to execute config operations.
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12. #include <errno.h>
  13. #include <assert.h>
  14. #include <sys/socket.h>
  15. #include <string.h>
  16. #include <sys/un.h>
  17. #include "clish/private.h"
  18. #include "private.h"
  19. #include "lub/string.h"
  20. #ifndef UNIX_PATH_MAX
  21. #define UNIX_PATH_MAX 108
  22. #endif
  23. conf_client_t *conf_client_new(char *path)
  24. {
  25. conf_client_t *client;
  26. if (!path)
  27. return NULL;
  28. if (!(client = malloc(sizeof(*client))))
  29. return NULL;
  30. client->sock = -1; /* socket is not created yet */
  31. client->path = lub_string_dup(path);
  32. return client;
  33. }
  34. void conf_client_free(conf_client_t *client)
  35. {
  36. if (client->sock != -1)
  37. conf_client_disconnect(client);
  38. lub_string_free(client->path);
  39. free(client);
  40. }
  41. int conf_client_connect(conf_client_t *client)
  42. {
  43. struct sockaddr_un raddr;
  44. if (client->sock >= 0)
  45. return client->sock;
  46. if ((client->sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  47. return client->sock;
  48. raddr.sun_family = AF_UNIX;
  49. strncpy(raddr.sun_path, client->path, UNIX_PATH_MAX);
  50. raddr.sun_path[UNIX_PATH_MAX - 1] = '\0';
  51. if (connect(client->sock, (struct sockaddr *)&raddr, sizeof(raddr))) {
  52. close(client->sock);
  53. client->sock = -1;
  54. }
  55. return client->sock;
  56. }
  57. void conf_client_disconnect(conf_client_t *client)
  58. {
  59. if (client->sock >= 0) {
  60. close(client->sock);
  61. client->sock = -1;
  62. }
  63. }
  64. int conf_client_reconnect(conf_client_t *client)
  65. {
  66. conf_client_disconnect(client);
  67. return conf_client_connect(client);
  68. }
  69. int conf_client_send(conf_client_t *client, char *command)
  70. {
  71. if (client->sock < 0)
  72. return client->sock;
  73. return send(client->sock, command, strlen(command) + 1, MSG_NOSIGNAL);
  74. }
  75. /*int conf_client_recv(conf_client_t *client, char *command)
  76. {
  77. if (client->sock < 0)
  78. return client->sock;
  79. return send(client->sock, command, strlen(command) + 1, 0);
  80. }
  81. */
  82. int conf_client__get_sock(conf_client_t *client)
  83. {
  84. return client->sock;
  85. }