network_interfaces_win.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/base/network_interfaces_win.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include "base/files/file_path.h"
  8. #include "base/lazy_instance.h"
  9. #include "base/strings/escape.h"
  10. #include "base/strings/string_piece.h"
  11. #include "base/strings/string_util.h"
  12. #include "base/strings/sys_string_conversions.h"
  13. #include "base/strings/utf_string_conversions.h"
  14. #include "base/threading/scoped_blocking_call.h"
  15. #include "base/threading/scoped_thread_priority.h"
  16. #include "base/win/scoped_handle.h"
  17. #include "net/base/ip_endpoint.h"
  18. #include "net/base/net_errors.h"
  19. #include "url/gurl.h"
  20. namespace net {
  21. namespace {
  22. // Converts Windows defined types to NetworkInterfaceType.
  23. NetworkChangeNotifier::ConnectionType GetNetworkInterfaceType(DWORD ifType) {
  24. NetworkChangeNotifier::ConnectionType type =
  25. NetworkChangeNotifier::CONNECTION_UNKNOWN;
  26. if (ifType == IF_TYPE_ETHERNET_CSMACD) {
  27. type = NetworkChangeNotifier::CONNECTION_ETHERNET;
  28. } else if (ifType == IF_TYPE_IEEE80211) {
  29. type = NetworkChangeNotifier::CONNECTION_WIFI;
  30. }
  31. // TODO(mallinath) - Cellular?
  32. return type;
  33. }
  34. // Returns scoped_ptr to WLAN_CONNECTION_ATTRIBUTES. The scoped_ptr may hold a
  35. // NULL pointer if WLAN_CONNECTION_ATTRIBUTES is unavailable.
  36. std::unique_ptr<WLAN_CONNECTION_ATTRIBUTES, internal::WlanApiDeleter>
  37. GetConnectionAttributes() {
  38. const internal::WlanApi& wlanapi = internal::WlanApi::GetInstance();
  39. std::unique_ptr<WLAN_CONNECTION_ATTRIBUTES, internal::WlanApiDeleter>
  40. wlan_connection_attributes;
  41. if (!wlanapi.initialized)
  42. return wlan_connection_attributes;
  43. internal::WlanHandle client;
  44. DWORD cur_version = 0;
  45. const DWORD kMaxClientVersion = 2;
  46. DWORD result = wlanapi.OpenHandle(kMaxClientVersion, &cur_version, &client);
  47. if (result != ERROR_SUCCESS)
  48. return wlan_connection_attributes;
  49. WLAN_INTERFACE_INFO_LIST* interface_list_ptr = nullptr;
  50. result =
  51. wlanapi.enum_interfaces_func(client.Get(), nullptr, &interface_list_ptr);
  52. if (result != ERROR_SUCCESS)
  53. return wlan_connection_attributes;
  54. std::unique_ptr<WLAN_INTERFACE_INFO_LIST, internal::WlanApiDeleter>
  55. interface_list(interface_list_ptr);
  56. // Assume at most one connected wifi interface.
  57. WLAN_INTERFACE_INFO* info = nullptr;
  58. for (unsigned i = 0; i < interface_list->dwNumberOfItems; ++i) {
  59. if (interface_list->InterfaceInfo[i].isState ==
  60. wlan_interface_state_connected) {
  61. info = &interface_list->InterfaceInfo[i];
  62. break;
  63. }
  64. }
  65. if (info == nullptr)
  66. return wlan_connection_attributes;
  67. WLAN_CONNECTION_ATTRIBUTES* conn_info_ptr = nullptr;
  68. DWORD conn_info_size = 0;
  69. WLAN_OPCODE_VALUE_TYPE op_code;
  70. result = wlanapi.query_interface_func(
  71. client.Get(), &info->InterfaceGuid, wlan_intf_opcode_current_connection,
  72. nullptr, &conn_info_size, reinterpret_cast<VOID**>(&conn_info_ptr),
  73. &op_code);
  74. wlan_connection_attributes.reset(conn_info_ptr);
  75. if (result == ERROR_SUCCESS)
  76. DCHECK(conn_info_ptr);
  77. else
  78. wlan_connection_attributes.reset();
  79. return wlan_connection_attributes;
  80. }
  81. } // namespace
  82. namespace internal {
  83. base::LazyInstance<WlanApi>::Leaky lazy_wlanapi =
  84. LAZY_INSTANCE_INITIALIZER;
  85. WlanApi& WlanApi::GetInstance() {
  86. return lazy_wlanapi.Get();
  87. }
  88. WlanApi::WlanApi() : initialized(false) {
  89. // Mitigate the issues caused by loading DLLs on a background thread
  90. // (http://crbug/973868).
  91. SCOPED_MAY_LOAD_LIBRARY_AT_BACKGROUND_PRIORITY();
  92. HMODULE module =
  93. ::LoadLibraryEx(L"wlanapi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
  94. if (!module)
  95. return;
  96. open_handle_func = reinterpret_cast<WlanOpenHandleFunc>(
  97. ::GetProcAddress(module, "WlanOpenHandle"));
  98. enum_interfaces_func = reinterpret_cast<WlanEnumInterfacesFunc>(
  99. ::GetProcAddress(module, "WlanEnumInterfaces"));
  100. query_interface_func = reinterpret_cast<WlanQueryInterfaceFunc>(
  101. ::GetProcAddress(module, "WlanQueryInterface"));
  102. set_interface_func = reinterpret_cast<WlanSetInterfaceFunc>(
  103. ::GetProcAddress(module, "WlanSetInterface"));
  104. free_memory_func = reinterpret_cast<WlanFreeMemoryFunc>(
  105. ::GetProcAddress(module, "WlanFreeMemory"));
  106. close_handle_func = reinterpret_cast<WlanCloseHandleFunc>(
  107. ::GetProcAddress(module, "WlanCloseHandle"));
  108. initialized = open_handle_func && enum_interfaces_func &&
  109. query_interface_func && set_interface_func &&
  110. free_memory_func && close_handle_func;
  111. }
  112. bool GetNetworkListImpl(NetworkInterfaceList* networks,
  113. int policy,
  114. const IP_ADAPTER_ADDRESSES* adapters) {
  115. for (const IP_ADAPTER_ADDRESSES* adapter = adapters; adapter != nullptr;
  116. adapter = adapter->Next) {
  117. // Ignore the loopback device.
  118. if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) {
  119. continue;
  120. }
  121. if (adapter->OperStatus != IfOperStatusUp) {
  122. continue;
  123. }
  124. // Ignore any HOST side vmware adapters with a description like:
  125. // VMware Virtual Ethernet Adapter for VMnet1
  126. // but don't ignore any GUEST side adapters with a description like:
  127. // VMware Accelerated AMD PCNet Adapter #2
  128. if ((policy & EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES) &&
  129. strstr(adapter->AdapterName, "VMnet") != nullptr) {
  130. continue;
  131. }
  132. for (IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress;
  133. address; address = address->Next) {
  134. int family = address->Address.lpSockaddr->sa_family;
  135. if (family == AF_INET || family == AF_INET6) {
  136. IPEndPoint endpoint;
  137. if (endpoint.FromSockAddr(address->Address.lpSockaddr,
  138. address->Address.iSockaddrLength)) {
  139. size_t prefix_length = address->OnLinkPrefixLength;
  140. // If the duplicate address detection (DAD) state is not changed to
  141. // Preferred, skip this address.
  142. if (address->DadState != IpDadStatePreferred) {
  143. continue;
  144. }
  145. uint32_t index =
  146. (family == AF_INET) ? adapter->IfIndex : adapter->Ipv6IfIndex;
  147. // From http://technet.microsoft.com/en-us/ff568768(v=vs.60).aspx, the
  148. // way to identify a temporary IPv6 Address is to check if
  149. // PrefixOrigin is equal to IpPrefixOriginRouterAdvertisement and
  150. // SuffixOrigin equal to IpSuffixOriginRandom.
  151. int ip_address_attributes = IP_ADDRESS_ATTRIBUTE_NONE;
  152. if (family == AF_INET6) {
  153. if (address->PrefixOrigin == IpPrefixOriginRouterAdvertisement &&
  154. address->SuffixOrigin == IpSuffixOriginRandom) {
  155. ip_address_attributes |= IP_ADDRESS_ATTRIBUTE_TEMPORARY;
  156. }
  157. if (address->PreferredLifetime == 0) {
  158. ip_address_attributes |= IP_ADDRESS_ATTRIBUTE_DEPRECATED;
  159. }
  160. }
  161. networks->push_back(NetworkInterface(
  162. adapter->AdapterName,
  163. base::SysWideToNativeMB(adapter->FriendlyName), index,
  164. GetNetworkInterfaceType(adapter->IfType), endpoint.address(),
  165. prefix_length, ip_address_attributes));
  166. }
  167. }
  168. }
  169. }
  170. return true;
  171. }
  172. } // namespace internal
  173. bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
  174. // Max number of times to retry GetAdaptersAddresses due to
  175. // ERROR_BUFFER_OVERFLOW. If GetAdaptersAddresses returns this indefinitely
  176. // due to an unforseen reason, we don't want to be stuck in an endless loop.
  177. static constexpr int MAX_GETADAPTERSADDRESSES_TRIES = 10;
  178. // Use an initial buffer size of 15KB, as recommended by MSDN. See:
  179. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365915(v=vs.85).aspx
  180. static constexpr int INITIAL_BUFFER_SIZE = 15000;
  181. ULONG len = INITIAL_BUFFER_SIZE;
  182. ULONG flags = 0;
  183. // Initial buffer allocated on stack.
  184. char initial_buf[INITIAL_BUFFER_SIZE];
  185. // Dynamic buffer in case initial buffer isn't large enough.
  186. std::unique_ptr<char[]> buf;
  187. IP_ADAPTER_ADDRESSES* adapters = nullptr;
  188. {
  189. // GetAdaptersAddresses() may require IO operations.
  190. base::ScopedBlockingCall scoped_blocking_call(
  191. FROM_HERE, base::BlockingType::MAY_BLOCK);
  192. adapters = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(&initial_buf);
  193. ULONG result =
  194. GetAdaptersAddresses(AF_UNSPEC, flags, nullptr, adapters, &len);
  195. // If we get ERROR_BUFFER_OVERFLOW, call GetAdaptersAddresses in a loop,
  196. // because the required size may increase between successive calls,
  197. // resulting in ERROR_BUFFER_OVERFLOW multiple times.
  198. for (int tries = 1; result == ERROR_BUFFER_OVERFLOW &&
  199. tries < MAX_GETADAPTERSADDRESSES_TRIES;
  200. ++tries) {
  201. buf = std::make_unique<char[]>(len);
  202. adapters = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buf.get());
  203. result = GetAdaptersAddresses(AF_UNSPEC, flags, nullptr, adapters, &len);
  204. }
  205. if (result == ERROR_NO_DATA) {
  206. // There are 0 networks.
  207. return true;
  208. } else if (result != NO_ERROR) {
  209. LOG(ERROR) << "GetAdaptersAddresses failed: " << result;
  210. return false;
  211. }
  212. }
  213. return internal::GetNetworkListImpl(networks, policy, adapters);
  214. }
  215. WifiPHYLayerProtocol GetWifiPHYLayerProtocol() {
  216. auto conn_info = GetConnectionAttributes();
  217. if (!conn_info.get())
  218. return WIFI_PHY_LAYER_PROTOCOL_NONE;
  219. switch (conn_info->wlanAssociationAttributes.dot11PhyType) {
  220. case dot11_phy_type_fhss:
  221. return WIFI_PHY_LAYER_PROTOCOL_ANCIENT;
  222. case dot11_phy_type_dsss:
  223. return WIFI_PHY_LAYER_PROTOCOL_B;
  224. case dot11_phy_type_irbaseband:
  225. return WIFI_PHY_LAYER_PROTOCOL_ANCIENT;
  226. case dot11_phy_type_ofdm:
  227. return WIFI_PHY_LAYER_PROTOCOL_A;
  228. case dot11_phy_type_hrdsss:
  229. return WIFI_PHY_LAYER_PROTOCOL_B;
  230. case dot11_phy_type_erp:
  231. return WIFI_PHY_LAYER_PROTOCOL_G;
  232. case dot11_phy_type_ht:
  233. return WIFI_PHY_LAYER_PROTOCOL_N;
  234. case dot11_phy_type_vht:
  235. return WIFI_PHY_LAYER_PROTOCOL_AC;
  236. case dot11_phy_type_dmg:
  237. return WIFI_PHY_LAYER_PROTOCOL_AD;
  238. case dot11_phy_type_he:
  239. return WIFI_PHY_LAYER_PROTOCOL_AX;
  240. default:
  241. return WIFI_PHY_LAYER_PROTOCOL_UNKNOWN;
  242. }
  243. }
  244. // Note: There is no need to explicitly set the options back
  245. // as the OS will automatically set them back when the WlanHandle
  246. // is closed.
  247. class WifiOptionSetter : public ScopedWifiOptions {
  248. public:
  249. WifiOptionSetter(int options) {
  250. const internal::WlanApi& wlanapi = internal::WlanApi::GetInstance();
  251. if (!wlanapi.initialized)
  252. return;
  253. DWORD cur_version = 0;
  254. const DWORD kMaxClientVersion = 2;
  255. DWORD result = wlanapi.OpenHandle(
  256. kMaxClientVersion, &cur_version, &client_);
  257. if (result != ERROR_SUCCESS)
  258. return;
  259. WLAN_INTERFACE_INFO_LIST* interface_list_ptr = nullptr;
  260. result = wlanapi.enum_interfaces_func(client_.Get(), nullptr,
  261. &interface_list_ptr);
  262. if (result != ERROR_SUCCESS)
  263. return;
  264. std::unique_ptr<WLAN_INTERFACE_INFO_LIST, internal::WlanApiDeleter>
  265. interface_list(interface_list_ptr);
  266. for (unsigned i = 0; i < interface_list->dwNumberOfItems; ++i) {
  267. WLAN_INTERFACE_INFO* info = &interface_list->InterfaceInfo[i];
  268. if (options & WIFI_OPTIONS_DISABLE_SCAN) {
  269. BOOL data = false;
  270. wlanapi.set_interface_func(client_.Get(), &info->InterfaceGuid,
  271. wlan_intf_opcode_background_scan_enabled,
  272. sizeof(data), &data, nullptr);
  273. }
  274. if (options & WIFI_OPTIONS_MEDIA_STREAMING_MODE) {
  275. BOOL data = true;
  276. wlanapi.set_interface_func(client_.Get(), &info->InterfaceGuid,
  277. wlan_intf_opcode_media_streaming_mode,
  278. sizeof(data), &data, nullptr);
  279. }
  280. }
  281. }
  282. private:
  283. internal::WlanHandle client_;
  284. };
  285. std::unique_ptr<ScopedWifiOptions> SetWifiOptions(int options) {
  286. return std::make_unique<WifiOptionSetter>(options);
  287. }
  288. std::string GetWifiSSID() {
  289. auto conn_info = GetConnectionAttributes();
  290. if (!conn_info.get())
  291. return "";
  292. const DOT11_SSID dot11_ssid = conn_info->wlanAssociationAttributes.dot11Ssid;
  293. return std::string(reinterpret_cast<const char*>(dot11_ssid.ucSSID),
  294. dot11_ssid.uSSIDLength);
  295. }
  296. } // namespace net