TUNInterface_linux.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  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. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "interface/tuntap/TUNInterface.h"
  16. #include "exception/Except.h"
  17. #include "memory/Allocator.h"
  18. #include "util/events/EventBase.h"
  19. #include "util/events/Pipe.h"
  20. #include <errno.h>
  21. #include <stdio.h>
  22. #include <sys/ioctl.h>
  23. #include <fcntl.h>
  24. #include <unistd.h>
  25. #include <sys/socket.h>
  26. #include <sys/types.h>
  27. #include <stdlib.h>
  28. #include <stddef.h>
  29. #include <net/if.h>
  30. #include <arpa/inet.h>
  31. #include <string.h>
  32. #include <linux/if.h>
  33. #include <linux/if_tun.h>
  34. #include <linux/if_ether.h>
  35. #if defined(android)
  36. #define DEVICE_PATH "/dev/tun"
  37. #else
  38. #define DEVICE_PATH "/dev/net/tun"
  39. #endif
  40. struct Iface* TUNInterface_new(const char* interfaceName,
  41. char assignedInterfaceName[TUNInterface_IFNAMSIZ],
  42. int isTapMode,
  43. struct EventBase* base,
  44. struct Log* logger,
  45. struct Except* eh,
  46. struct Allocator* alloc)
  47. {
  48. uint32_t maxNameSize = (IFNAMSIZ < TUNInterface_IFNAMSIZ) ? IFNAMSIZ : TUNInterface_IFNAMSIZ;
  49. Log_info(logger, "Initializing tun device [%s]", ((interfaceName) ? interfaceName : "auto"));
  50. struct ifreq ifRequest = { .ifr_flags = (isTapMode) ? IFF_TAP : IFF_TUN };
  51. if (interfaceName) {
  52. if (strlen(interfaceName) > maxNameSize) {
  53. Except_throw(eh, "tunnel name too big, limit is [%d] characters", maxNameSize);
  54. }
  55. strncpy(ifRequest.ifr_name, interfaceName, maxNameSize);
  56. }
  57. int fileno = open(DEVICE_PATH, O_RDWR);
  58. if (fileno < 0) {
  59. Except_throw(eh, "open(\"%s\") [%s]", DEVICE_PATH, strerror(errno));
  60. }
  61. if (ioctl(fileno, TUNSETIFF, &ifRequest) < 0) {
  62. int err = errno;
  63. close(fileno);
  64. Except_throw(eh, "ioctl(TUNSETIFF) [%s]", strerror(err));
  65. }
  66. if (assignedInterfaceName) {
  67. strncpy(assignedInterfaceName, ifRequest.ifr_name, maxNameSize);
  68. }
  69. struct Pipe* p = Pipe_forFiles(fileno, fileno, base, eh, alloc);
  70. return &p->iface;
  71. }