tun_interface.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /*
  2. * Copyright 2017 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. * tun_interface.cpp - creates tun interfaces for testing purposes
  17. */
  18. #include <string>
  19. #include <fcntl.h>
  20. #include <linux/if.h>
  21. #include <linux/if_tun.h>
  22. #include <linux/netlink.h>
  23. #include <linux/rtnetlink.h>
  24. #include <net/if.h>
  25. #include <netdb.h>
  26. #include <netinet/in.h>
  27. #include <stdlib.h>
  28. #include <sys/ioctl.h>
  29. #include <sys/socket.h>
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #include <unistd.h>
  33. #include <android-base/stringprintf.h>
  34. #include <android-base/strings.h>
  35. #include <android-base/unique_fd.h>
  36. #include <netutils/ifc.h>
  37. #include "tun_interface.h"
  38. #define TUN_DEV "/dev/tun"
  39. using android::base::StringPrintf;
  40. using android::base::unique_fd;
  41. namespace android {
  42. namespace net {
  43. int TunInterface::init(const std::string& ifName) {
  44. // Generate a random ULA address pair.
  45. arc4random_buf(&mSrcAddr, sizeof(mSrcAddr));
  46. mSrcAddr.s6_addr[0] = 0xfd;
  47. memcpy(&mDstAddr, &mSrcAddr, sizeof(mDstAddr));
  48. mDstAddr.s6_addr[15] ^= 1;
  49. // Convert the addresses to strings because that's what ifc_add_address takes.
  50. char srcStr[INET6_ADDRSTRLEN], dstStr[INET6_ADDRSTRLEN];
  51. sockaddr_in6 src6 = { .sin6_family = AF_INET6, .sin6_addr = mSrcAddr, };
  52. sockaddr_in6 dst6 = { .sin6_family = AF_INET6, .sin6_addr = mDstAddr, };
  53. int flags = NI_NUMERICHOST;
  54. if (getnameinfo((sockaddr *) &src6, sizeof(src6), srcStr, sizeof(srcStr), nullptr, 0, flags) ||
  55. getnameinfo((sockaddr *) &dst6, sizeof(dst6), dstStr, sizeof(dstStr), nullptr, 0, flags)) {
  56. return -EINVAL;
  57. }
  58. // Create a tun interface with a name based on a random number.
  59. // In order to fit the size of interface alert name , resize ifname to 9
  60. // Alert name format in netd: ("%sAlert", ifname)
  61. // Limitation in kernel: char name[15] in struct xt_quota_mtinfo2
  62. // Note that this form of alert doesn't actually appear to be used for interface alerts.
  63. // It can only be created by BandwidthController::setInterfaceAlert, but that appears to have no
  64. // actual callers in the framework, because mActiveAlerts is always empty.
  65. // TODO: remove setInterfaceAlert and use a longer interface name.
  66. mIfName = ifName;
  67. if (mIfName.empty()) {
  68. mIfName = StringPrintf("netd%x", arc4random());
  69. }
  70. mIfName.resize(9);
  71. struct ifreq ifr = {
  72. .ifr_ifru = { .ifru_flags = IFF_TUN },
  73. };
  74. strlcpy(ifr.ifr_name, mIfName.c_str(), sizeof(ifr.ifr_name));
  75. mFd = open(TUN_DEV, O_RDWR | O_NONBLOCK | O_CLOEXEC);
  76. if (mFd == -1) return -errno;
  77. int ret = ioctl(mFd, TUNSETIFF, &ifr, sizeof(ifr));
  78. if (ret == -1) {
  79. ret = -errno;
  80. close(mFd);
  81. return ret;
  82. }
  83. mIfIndex = if_nametoindex(ifr.ifr_name);
  84. if (addAddress(srcStr, 64) || addAddress(dstStr, 64)) {
  85. ret = -errno;
  86. close(mFd);
  87. return ret;
  88. }
  89. if (int ret = ifc_enable(ifr.ifr_name)) {
  90. return ret;
  91. }
  92. return 0;
  93. }
  94. void TunInterface::destroy() {
  95. if (mFd != -1) {
  96. ifc_disable(mIfName.c_str());
  97. close(mFd);
  98. mFd = -1;
  99. }
  100. }
  101. int TunInterface::addAddress(const std::string& addr, int prefixlen) {
  102. // Wait for an RTM_NEWADDR indicating that the address has been created.
  103. // This is because IPv6 addresses, even addresses that are optimistic or created with
  104. // IFA_F_NODAD, are not immediately usable when the netlink ACK returns.
  105. // This is not generally necessary in device code because the framework hears about IP addresses
  106. // asynchronously via netlink, but it is necessary to ensure tests aren't flaky.
  107. unique_fd s(socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, 0));
  108. if (s == -1) return -errno;
  109. sockaddr_nl groups = {.nl_family = AF_NETLINK,
  110. .nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR};
  111. if (bind(s, reinterpret_cast<sockaddr*>(&groups), sizeof(groups)) == -1) return -errno;
  112. sockaddr_nl kernel = {.nl_family = AF_NETLINK};
  113. if (connect(s, reinterpret_cast<sockaddr*>(&kernel), sizeof(kernel)) == -1) return -errno;
  114. // Wait up to 200ms for address to arrive.
  115. timeval timeout = {.tv_usec = 200 * 1000};
  116. if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) return -errno;
  117. if (ifc_add_address(mIfName.c_str(), addr.c_str(), prefixlen)) return -errno;
  118. int family;
  119. size_t addrlen;
  120. union {
  121. in_addr ip4;
  122. in6_addr ip6;
  123. } ip;
  124. if (addr.find(':') != std::string::npos) {
  125. family = AF_INET6;
  126. inet_pton(AF_INET6, addr.c_str(), &ip.ip6);
  127. addrlen = sizeof(ip.ip6);
  128. } else {
  129. family = AF_INET;
  130. inet_pton(AF_INET, addr.c_str(), &ip.ip4);
  131. addrlen = sizeof(ip.ip4);
  132. }
  133. while (1) {
  134. char buf[4096];
  135. ssize_t len = recv(s, buf, sizeof(buf), 0);
  136. if (len == -1) break;
  137. if (len < static_cast<ssize_t>(NLMSG_SPACE(sizeof(ifaddrmsg)))) continue;
  138. nlmsghdr* nlmsg = reinterpret_cast<nlmsghdr*>(buf);
  139. if (nlmsg->nlmsg_type != RTM_NEWADDR) continue;
  140. ifaddrmsg* ifaddr = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(nlmsg));
  141. if (ifaddr->ifa_family != family) continue;
  142. if (ifaddr->ifa_prefixlen != prefixlen) continue;
  143. if (ifaddr->ifa_index != static_cast<uint32_t>(mIfIndex)) continue;
  144. int ifalen = IFA_PAYLOAD(nlmsg);
  145. for (rtattr* rta = IFA_RTA(ifaddr); RTA_OK(rta, ifalen); rta = RTA_NEXT(rta, ifalen)) {
  146. if (rta->rta_type != IFA_LOCAL && rta->rta_type != IFA_ADDRESS) continue;
  147. if (RTA_PAYLOAD(rta) != addrlen) continue;
  148. if (!memcmp(RTA_DATA(rta), &ip, addrlen)) {
  149. return 0;
  150. }
  151. }
  152. }
  153. return -errno;
  154. }
  155. } // namespace net
  156. } // namespace android