Skip to content

Commit

Permalink
Make sure got IP from hotspot
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 719393670
  • Loading branch information
ggli-google authored and copybara-github committed Jan 24, 2025
1 parent ed65627 commit bf87b5a
Show file tree
Hide file tree
Showing 10 changed files with 125 additions and 76 deletions.
8 changes: 3 additions & 5 deletions connections/implementation/mediums/wifi_hotspot.cc
Original file line number Diff line number Diff line change
Expand Up @@ -100,17 +100,15 @@ bool WifiHotspot::IsConnectedToHotspot() {
return is_connected_to_hotspot_;
}

bool WifiHotspot::ConnectWifiHotspot(const std::string& ssid,
const std::string& password,
int frequency) {
bool WifiHotspot::ConnectWifiHotspot(
const HotspotCredentials& hotspot_credentials) {
MutexLock lock(&mutex_);
if (is_connected_to_hotspot_) {
NEARBY_LOGS(INFO)
<< "No need to connect to Hotspot because it is already connected.";
return true;
}
is_connected_to_hotspot_ =
medium_.ConnectWifiHotspot(ssid, password, frequency);
is_connected_to_hotspot_ = medium_.ConnectWifiHotspot(hotspot_credentials);
return is_connected_to_hotspot_;
}

Expand Down
4 changes: 2 additions & 2 deletions connections/implementation/mediums/wifi_hotspot.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ class WifiHotspot {
bool StopWifiHotspot() ABSL_LOCKS_EXCLUDED(mutex_);

bool IsConnectedToHotspot() ABSL_LOCKS_EXCLUDED(mutex_);
bool ConnectWifiHotspot(const std::string& ssid, const std::string& password,
int frequency) ABSL_LOCKS_EXCLUDED(mutex_);
bool ConnectWifiHotspot(const HotspotCredentials& hotspot_credentials)
ABSL_LOCKS_EXCLUDED(mutex_);
bool DisconnectWifiHotspot() ABSL_LOCKS_EXCLUDED(mutex_);

// Starts a worker thread, creates a WifiHotspot socket, associates it with a
Expand Down
27 changes: 11 additions & 16 deletions connections/implementation/mediums/wifi_hotspot_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@ class WifiHotspotTest : public testing::TestWithParam<FeatureFlags> {
env_.Stop();
env_.Start();
}
~WifiHotspotTest() override{
env_.Stop();
}
~WifiHotspotTest() override { env_.Stop(); }

MediumEnvironment& env_{MediumEnvironment::Instance()};
};
Expand Down Expand Up @@ -89,10 +87,11 @@ TEST_F(WifiHotspotTest, CanStartStopHotspot) {

TEST_F(WifiHotspotTest, CanConnectDisconnectHotspot) {
auto wifi_hotspot_a = std::make_unique<WifiHotspot>();
std::string ssid(kSsid);
std::string password(kPassword);
HotspotCredentials hotspot_credentials;
hotspot_credentials.SetSSID(std::string(kSsid));
hotspot_credentials.SetPassword(std::string(kPassword));

EXPECT_FALSE(wifi_hotspot_a->ConnectWifiHotspot(ssid, password, kFrequency));
EXPECT_FALSE(wifi_hotspot_a->ConnectWifiHotspot(hotspot_credentials));
EXPECT_TRUE(wifi_hotspot_a->DisconnectWifiHotspot());
}

Expand All @@ -113,9 +112,7 @@ TEST_P(WifiHotspotTest, CanStartHotspotThatOtherConnect) {
HotspotCredentials* hotspot_credentials =
wifi_hotspot_a->GetCredentials(service_id);

EXPECT_TRUE(wifi_hotspot_b->ConnectWifiHotspot(
hotspot_credentials->GetSSID(), hotspot_credentials->GetPassword(),
hotspot_credentials->GetFrequency()));
EXPECT_TRUE(wifi_hotspot_b->ConnectWifiHotspot(*hotspot_credentials));

WifiHotspotSocket socket_client;
EXPECT_FALSE(socket_client.IsValid());
Expand Down Expand Up @@ -152,9 +149,7 @@ TEST_P(WifiHotspotTest, CanStartHotspotThatOtherCanCancelConnect) {
HotspotCredentials* hotspot_credentials =
wifi_hotspot_a->GetCredentials(service_id);

EXPECT_TRUE(wifi_hotspot_b->ConnectWifiHotspot(
hotspot_credentials->GetSSID(), hotspot_credentials->GetPassword(),
hotspot_credentials->GetFrequency()));
EXPECT_TRUE(wifi_hotspot_b->ConnectWifiHotspot(*hotspot_credentials));

WifiHotspotSocket socket_client;
EXPECT_FALSE(socket_client.IsValid());
Expand Down Expand Up @@ -183,10 +178,10 @@ TEST_F(WifiHotspotTest, CanStartHotspotTheOtherFailConnect) {

EXPECT_TRUE(wifi_hotspot_a->StartWifiHotspot());

std::string ssid(kSsid);
std::string password(kPassword);

EXPECT_FALSE(wifi_hotspot_b->ConnectWifiHotspot(ssid, password, kFrequency));
HotspotCredentials hotspot_credentials;
hotspot_credentials.SetSSID(std::string(kSsid));
hotspot_credentials.SetPassword(std::string(kPassword));
EXPECT_FALSE(wifi_hotspot_b->ConnectWifiHotspot(hotspot_credentials));
EXPECT_TRUE(wifi_hotspot_b->DisconnectWifiHotspot());

EXPECT_TRUE(wifi_hotspot_a->StopWifiHotspot());
Expand Down
59 changes: 33 additions & 26 deletions connections/implementation/wifi_hotspot_bwu_handler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ ByteArray WifiHotspotBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
const std::string& endpoint_id) {
// Create SoftAP
if (!wifi_hotspot_medium_.StartWifiHotspot()) {
NEARBY_LOGS(INFO) << "Failed to start Wifi Hotspot!";
LOG(INFO) << "Failed to start Wifi Hotspot!";
return {};
}

Expand All @@ -63,14 +63,14 @@ ByteArray WifiHotspotBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
absl::bind_front(
&WifiHotspotBwuHandler::OnIncomingWifiHotspotConnection, this,
client))) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "WifiHotspotBwuHandler couldn't initiate WifiHotspot upgrade for "
<< "service " << upgrade_service_id << " and endpoint " << endpoint_id
<< " because it failed to start listening for incoming WifiLan "
"connections.";
return {};
}
NEARBY_LOGS(INFO)
LOG(INFO)
<< "WifiHotspotBwuHandler successfully started listening for incoming "
"WifiHotspot connections while upgrading endpoint "
<< endpoint_id;
Expand All @@ -87,9 +87,9 @@ ByteArray WifiHotspotBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
std::int32_t port = hotspot_crendential->GetPort();
std::int32_t frequency = hotspot_crendential->GetFrequency();

NEARBY_LOGS(INFO) << "Start SoftAP with SSID:" << ssid
<< ", Password:" << password << ", Port:" << port
<< ", Gateway:" << gateway << ", Frequency:" << frequency;
LOG(INFO) << "Start SoftAP with SSID:" << ssid << ", Password:" << password
<< ", Port:" << port << ", Gateway:" << gateway
<< ", Frequency:" << frequency;

bool disabling_encryption =
(client->GetAdvertisingOptions().strategy == Strategy::kP2pPointToPoint);
Expand All @@ -104,9 +104,8 @@ void WifiHotspotBwuHandler::HandleRevertInitiatorStateForService(
wifi_hotspot_medium_.StopWifiHotspot();
wifi_hotspot_medium_.DisconnectWifiHotspot();

NEARBY_LOGS(INFO)
<< "WifiHotspotBwuHandler successfully reverted all states for "
<< "upgrade service ID " << upgrade_service_id;
LOG(INFO) << "WifiHotspotBwuHandler successfully reverted all states for "
<< "upgrade service ID " << upgrade_service_id;
}

// Called by BWU target. Retrieves a new medium info from incoming message,
Expand All @@ -116,41 +115,49 @@ WifiHotspotBwuHandler::CreateUpgradedEndpointChannel(
ClientProxy* client, const std::string& service_id,
const std::string& endpoint_id, const UpgradePathInfo& upgrade_path_info) {
if (!upgrade_path_info.has_wifi_hotspot_credentials()) {
NEARBY_LOGS(INFO) << "No Hotspot Credential";
LOG(INFO) << "No Hotspot Credential";
return {Error(
OperationResultCode::CONNECTIVITY_WIFI_HOTSPOT_INVALID_CREDENTIAL)};
}
const UpgradePathInfo::WifiHotspotCredentials& upgrade_path_info_credentials =
upgrade_path_info.wifi_hotspot_credentials();

const std::string& ssid = upgrade_path_info_credentials.ssid();
const std::string& password = upgrade_path_info_credentials.password();
const std::string& gateway = upgrade_path_info_credentials.gateway();
std::int32_t port = upgrade_path_info_credentials.port();
std::int32_t frequency = upgrade_path_info_credentials.frequency();

NEARBY_LOGS(INFO) << "Received Hotspot credential SSID: " << ssid
<< ", Password:" << password << ", Port:" << port
<< ", Gateway:" << gateway << ", Frequency:" << frequency;

if (!wifi_hotspot_medium_.ConnectWifiHotspot(ssid, password, frequency)) {
NEARBY_LOGS(ERROR) << "Connect to Hotspot failed";
HotspotCredentials hotspot_credentials;
hotspot_credentials.SetSSID(upgrade_path_info_credentials.ssid());
hotspot_credentials.SetPassword(upgrade_path_info_credentials.password());
hotspot_credentials.SetGateway(upgrade_path_info_credentials.gateway());
hotspot_credentials.SetPort(upgrade_path_info_credentials.port());
hotspot_credentials.SetFrequency(upgrade_path_info_credentials.frequency());

LOG(INFO) << "Received Hotspot credential SSID: "
<< hotspot_credentials.GetSSID()
<< ", Password:" << hotspot_credentials.GetPassword()
<< ", Port:" << hotspot_credentials.GetPort()
<< ", Gateway:" << hotspot_credentials.GetGateway()
<< ", Frequency:" << hotspot_credentials.GetFrequency();

if (!wifi_hotspot_medium_.ConnectWifiHotspot(hotspot_credentials)) {
LOG(ERROR) << "Connect to Hotspot failed";
return {Error(
OperationResultCode::CONNECTIVITY_WIFI_HOTSPOT_INVALID_CREDENTIAL)};
}

ErrorOr<WifiHotspotSocket> socket_result = wifi_hotspot_medium_.Connect(
service_id, gateway, port, client->GetCancellationFlag(endpoint_id));
service_id, hotspot_credentials.GetGateway(),
hotspot_credentials.GetPort(), client->GetCancellationFlag(endpoint_id));
if (socket_result.has_error()) {
NEARBY_LOGS(ERROR)
LOG(ERROR)
<< "WifiHotspotBwuHandler failed to connect to the WifiHotspot service("
<< gateway << ":" << port << ") for endpoint " << endpoint_id;
<< hotspot_credentials.GetGateway() << ":"
<< hotspot_credentials.GetPort() << ") for endpoint " << endpoint_id;
return {Error(socket_result.error().operation_result_code().value())};
}

NEARBY_VLOG(1)
<< "WifiHotspotBwuHandler successfully connected to WifiHotspot service ("
<< gateway << ":" << port << ") while upgrading endpoint " << endpoint_id;
<< hotspot_credentials.GetGateway() << ":"
<< hotspot_credentials.GetPort() << ") while upgrading endpoint "
<< endpoint_id;

// Create a new WifiHotspotEndpointChannel.
auto channel = std::make_unique<WifiHotspotEndpointChannel>(
Expand Down
33 changes: 33 additions & 0 deletions internal/platform/implementation/windows/utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,39 @@ std::vector<std::string> Get4BytesIpv4Addresses() {
return result;
}

std::vector<std::string> GetWifiIpv4Addresses() {
std::vector<std::string> result;

try {
auto host_names = NetworkInformation::GetHostNames();
for (const auto& host_name : host_names) {
if (host_name.IPInformation() != nullptr &&
host_name.IPInformation().NetworkAdapter() != nullptr &&
host_name.Type() == HostNameType::Ipv4) {
NetworkAdapter adapter = host_name.IPInformation().NetworkAdapter();
if (adapter.NetworkItem().GetNetworkTypes() == NetworkTypes::None) {
// If we're not connected to a network, we don't want to add this
// address.
continue;
}
if (adapter.IanaInterfaceType() == Constants::kInterfaceTypeWifi) {
result.push_back(winrt::to_string(host_name.ToString()));
}
}
}
} catch (std::exception exception) {
LOG(ERROR) << __func__ << ": Cannot get IPv4 addresses. Exception : "
<< exception.what();
} catch (const winrt::hresult_error& error) {
LOG(ERROR) << __func__ << ": Cannot get IPv4 addresses. WinRT exception: "
<< error.code() << ": " << winrt::to_string(error.message());
} catch (...) {
LOG(ERROR) << __func__ << ": Unknown exeption.";
}

return result;
}

Uuid winrt_guid_to_nearby_uuid(const ::winrt::guid& guid) {
int64_t data1 = guid.Data1;
int64_t data2 = guid.Data2;
Expand Down
4 changes: 3 additions & 1 deletion internal/platform/implementation/windows/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#include <windows.h>

#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
Expand Down Expand Up @@ -44,14 +45,15 @@ ByteArray Sha256(absl::string_view input, size_t size);
// Reads the IPv4 addresses
std::vector<std::string> GetIpv4Addresses();
std::vector<std::string> Get4BytesIpv4Addresses();
std::vector<std::string> GetWifiIpv4Addresses();

// Help methods to convert between Uuid and winrt::guid
Uuid winrt_guid_to_nearby_uuid(const ::winrt::guid& guid);
winrt::guid nearby_uuid_to_winrt_guid(Uuid uuid);

// Check whether Uuid and guid is the same value.
bool is_nearby_uuid_equal_to_winrt_guid(const Uuid& uuid,
const ::winrt::guid& guid);
const ::winrt::guid& guid);

namespace Constants {
// The Id of the Service Name SDP attribute
Expand Down
20 changes: 17 additions & 3 deletions internal/platform/implementation/windows/wifi_hotspot_medium.cc
Original file line number Diff line number Diff line change
Expand Up @@ -718,18 +718,32 @@ bool WifiHotspotMedium::ConnectWifiHotspotWithNative(

// Make sure IP address is ready.
std::string ip_address;
int64_t ip_address_max_retries = 20;
int64_t ip_address_retry_interval_millis = 500;
int64_t ip_address_max_retries = NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotCheckIpMaxRetries);
int64_t ip_address_retry_interval_millis =
NearbyFlags::GetInstance().GetInt64Flag(
platform::config_package_nearby::nearby_platform_feature::
kWifiHotspotCheckIpIntervalMillis);
LOG(INFO) << "maximum IP check retries=" << ip_address_max_retries
<< ", IP check interval=" << ip_address_retry_interval_millis
<< "ms";
for (int i = 0; i < ip_address_max_retries; i++) {
LOG(INFO) << "Check IP address at attempt " << i;
std::vector<std::string> ip_addresses = GetIpv4Addresses();
std::vector<std::string> ip_addresses = GetWifiIpv4Addresses();

if (ip_addresses.empty()) {
Sleep(ip_address_retry_interval_millis);
continue;
}

// Need to filter out the APIPA address("169.254.x.x").
if (ip_addresses[0].starts_with("169.254.")) {
LOG(WARNING) << "Got APIPA address " << ip_addresses[0];
Sleep(ip_address_retry_interval_millis);
continue;
}

ip_address = ip_addresses[0];
break;
}
Expand Down
8 changes: 5 additions & 3 deletions internal/platform/wifi_hotspot.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@

#include "internal/platform/wifi_hotspot.h"

#include "internal/platform/mutex_lock.h"
#include "absl/strings/string_view.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/logging.h"

namespace nearby {

WifiHotspotSocket WifiHotspotMedium::ConnectToService(
absl::string_view ip_address, int port,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(INFO) << "WifiHotspotMedium::ConnectToService: ip address="
<< ip_address << ", port=" << port;
LOG(INFO) << "WifiHotspotMedium::ConnectToService: ip address=" << ip_address
<< ", port=" << port;
return WifiHotspotSocket(
impl_->ConnectToService(ip_address, port, cancellation_flag));
}
Expand Down
12 changes: 4 additions & 8 deletions internal/platform/wifi_hotspot.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <string>
#include <utility>

#include "absl/base/thread_annotations.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "internal/platform/cancellation_flag.h"
Expand Down Expand Up @@ -183,19 +184,14 @@ class WifiHotspotMedium {
}
bool StopWifiHotspot() { return impl_->StopWifiHotspot(); }

bool ConnectWifiHotspot(const std::string& ssid,
const std::string& password, int frequency) {
bool ConnectWifiHotspot(const HotspotCredentials& hotspot_credentials) {
MutexLock lock(&mutex_);
hotspot_credentials_.SetSSID(ssid);
hotspot_credentials_.SetPassword(password);
hotspot_credentials_.SetFrequency(frequency);
hotspot_credentials_ = hotspot_credentials;
return impl_->ConnectWifiHotspot(&hotspot_credentials_);
}
bool DisconnectWifiHotspot() { return impl_->DisconnectWifiHotspot(); }

HotspotCredentials* GetCredential() {
return &hotspot_credentials_;
}
HotspotCredentials* GetCredential() { return &hotspot_credentials_; }

bool IsInterfaceValid() const {
CHECK(impl_);
Expand Down
Loading

0 comments on commit bf87b5a

Please sign in to comment.