net.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 "lub/string.h"
  19. #ifndef UNIX_PATH_MAX
  20. #define UNIX_PATH_MAX 108
  21. #endif
  22. conf_client_t *conf_client_new(char *path)
  23. {
  24. conf_client_t *client;
  25. if (!path)
  26. return NULL;
  27. if (!(client = malloc(sizeof(*client))))
  28. return NULL;
  29. client->sock = -1; /* socket is not created yet */
  30. client->path = lub_string_dup(path);
  31. return client;
  32. }
  33. void conf_client_free(conf_client_t *client)
  34. {
  35. if (client->sock != -1)
  36. conf_client_disconnect(client);
  37. lub_string_free(client->path);
  38. free(client);
  39. }
  40. int conf_client_connect(conf_client_t *client)
  41. {
  42. struct sockaddr_un raddr;
  43. if (client->sock >= 0)
  44. return client->sock;
  45. if ((client->sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  46. return client->sock;
  47. raddr.sun_family = AF_UNIX;
  48. strncpy(raddr.sun_path, client->path, UNIX_PATH_MAX);
  49. raddr.sun_path[UNIX_PATH_MAX - 1] = '\0';
  50. if (connect(client->sock, (struct sockaddr *)&raddr, sizeof(raddr))) {
  51. close(client->sock);
  52. client->sock = -1;
  53. }
  54. return client->sock;
  55. }
  56. void conf_client_disconnect(conf_client_t *client)
  57. {
  58. if (client->sock >= 0) {
  59. close(client->sock);
  60. client->sock = -1;
  61. }
  62. }
  63. int conf_client_reconnect(conf_client_t *client)
  64. {
  65. conf_client_disconnect(client);
  66. return conf_client_connect(client);
  67. }
  68. int conf_client_send(conf_client_t *client, char *command)
  69. {
  70. if (client->sock < 0)
  71. return client->sock;
  72. return send(client->sock, command, strlen(command) + 1, MSG_NOSIGNAL);
  73. }
  74. /*int conf_client_recv(conf_client_t *client, char *command)
  75. {
  76. if (client->sock < 0)
  77. return client->sock;
  78. return send(client->sock, command, strlen(command) + 1, 0);
  79. }
  80. */
  81. int conf_client__get_sock(conf_client_t *client)
  82. {
  83. return client->sock;
  84. }