relay.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /* vccd/relay.c
  2. *
  3. * This file is part of vccd.
  4. *
  5. * vccd is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * vccd is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with vccd. If not, see <https://www.gnu.org/licenses/>
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #include <errno.h>
  23. #include <string.h>
  24. #include <sys/stat.h>
  25. #include <sys/types.h>
  26. #include <sys/socket.h>
  27. #include <netinet/in.h>
  28. #include <arpa/inet.h>
  29. #include <poll.h>
  30. #include <vcc/vcc.h>
  31. #include <vcc/vccd.h>
  32. #include <vcc/version.h>
  33. #include <klist.h>
  34. extern struct klist_node connections;
  35. int relay_new_msg(int fd, void *t) {
  36. struct vcc_relay_header *req;
  37. char *msg;
  38. int len;
  39. req = t;
  40. len = ntohl(req->size) - sizeof(struct vcc_relay_header);
  41. if (unlikely(!(msg = amalloc(len)))) {
  42. fprintf(stderr, "*** malloc() failed\n");
  43. return 1;
  44. }
  45. read_until(fd, msg, len);
  46. relay_send_to(msg, 0, req);
  47. return 0;
  48. }
  49. int relay_send_to(const char *msg, int expect_fd, struct vcc_relay_header *hdr) {
  50. struct vcc_relay_header *req;
  51. struct klist_node *n;
  52. int i, len;
  53. /* make sure about that the write() bottom will execute after these */
  54. vcc_write_all();
  55. i = 0;
  56. len = strlen(msg);
  57. for (n = connections.next; n != &connections; n = n->next) {
  58. if (n->value == expect_fd)
  59. continue;
  60. if (unlikely(!(req = amalloc(sizeof(struct vcc_relay_header))))) {
  61. vcc_log("*** malloc() failed\n");
  62. return 1;
  63. }
  64. memset(req, 0, sizeof(struct vcc_relay_header));
  65. req->magic = htonl(VCC_MAGIC_RL);
  66. req->reqtype = htonl(REQ_REL_NEW);
  67. req->uid = 0;
  68. req->session = 0;
  69. req->size = htonl(sizeof(struct vcc_relay_header) + len);
  70. strncpy(req->usrname, hdr->usrname, USRNAME_SIZE);
  71. /* direct writes here
  72. * vcc_send_req(n, req);
  73. * */
  74. write(n->value, req, sizeof(struct vcc_relay_header));
  75. write(n->value, msg, len);
  76. i++;
  77. }
  78. vcc_log("Relay message sent to %d users. \n", i);
  79. return 0;
  80. }