inet.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 <errno.h>
  16. #include <netinet/in.h>
  17. #include <sys/socket.h>
  18. static const int sHT_true = 1;
  19. static int
  20. sHT_enable_sockopt(int fd, int layer, int flag)
  21. {
  22. return setsockopt(fd, layer, flag, &sHT_true, sizeof(sHT_true));
  23. }
  24. int
  25. sHT_passive_ipv6(const struct sHT_passive_in6 *in)
  26. {
  27. int fd = socket(AF_INET6, in->type, 0);
  28. if (sHT_unlikely(sHT_test_hidden(fd, fd < 0)))
  29. return -errno;
  30. int ret = sHT_enable_sockopt(fd, IPPROTO_IP, IP_FREEBIND);
  31. if (sHT_unlikely(sHT_test_hidden(ret, ret)))
  32. goto socket;
  33. ret = sHT_enable_sockopt(fd, SOL_SOCKET, SO_REUSEPORT);
  34. if (sHT_unlikely(sHT_test_hidden(ret, ret)))
  35. goto socket;
  36. /* XXX SO_ATTACH_BPF (seccomp filtering) */
  37. ret = bind(fd, (struct sockaddr *) &in->addr, sizeof(in->addr));
  38. if (sHT_unlikely(sHT_test_hidden(ret, ret < 0)))
  39. goto socket;
  40. ret = listen(fd, in->backlog);
  41. if (sHT_unlikely(sHT_test_hidden(ret, ret < 0)))
  42. goto socket;
  43. return fd;
  44. socket:
  45. ret = -errno;
  46. sHT_close(fd);
  47. return ret;
  48. }