inet.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* shttpd - connecting to the internet
  2. Copyright (C) 2018 Ariadne Devos
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #include "fd.h"
  14. #include <sHT/compiler.h>
  15. #include <sHT/test.h>
  16. #include <errno.h>
  17. #include <netinet/in.h>
  18. #include <sys/socket.h>
  19. static const int sHT_true = 1;
  20. static int
  21. sHT_enable_sockopt(int fd, int layer, int flag)
  22. {
  23. return setsockopt(fd, layer, flag, &sHT_true, sizeof(sHT_true));
  24. }
  25. int
  26. sHT_passive_ipv6(const struct sHT_passive_in6 *in)
  27. {
  28. int fd = socket(AF_INET6, in->type, 0);
  29. if (sHT_lt0(fd))
  30. return -errno;
  31. int ret = sHT_enable_sockopt(fd, IPPROTO_IP, IP_FREEBIND);
  32. if (sHT_nonzero_p(ret))
  33. goto socket;
  34. ret = sHT_enable_sockopt(fd, SOL_SOCKET, SO_REUSEPORT);
  35. if (sHT_nonzero_p(ret))
  36. goto socket;
  37. /* XXX SO_ATTACH_BPF (seccomp filtering) */
  38. ret = bind(fd, (struct sockaddr *) &in->addr, sizeof(in->addr));
  39. if (sHT_lt0(ret))
  40. goto socket;
  41. ret = listen(fd, in->backlog);
  42. if (sHT_lt0(ret))
  43. goto socket;
  44. return fd;
  45. socket:
  46. ret = -errno;
  47. sHT_close(fd);
  48. return ret;
  49. }