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