nearbyconnections : Implement WifiLanV2 Connection functions for /medium, /public(wrapper), /g3.

PiperOrigin-RevId: 405820452
This commit is contained in:
edwinwu
2021-10-26 23:39:26 -07:00
committed by Copybara-Service
parent 83480d6473
commit 7197b84e4d
15 changed files with 726 additions and 63 deletions
+1
View File
@@ -103,6 +103,7 @@ cc_test(
"//testing/base/public:gunit_main",
"//absl/strings",
"//absl/time",
"//platform/base",
"//platform/base:test_util",
"//platform/impl/g3", # build_cleaner: keep
"//platform/public:comm",
@@ -19,6 +19,7 @@
#include "absl/strings/string_view.h"
#include "core/internal/mediums/wifi_lan_v2.h"
#include "platform/base/medium_environment.h"
#include "platform/base/nsd_service_info.h"
#include "platform/public/count_down_latch.h"
#include "platform/public/logging.h"
#include "platform/public/wifi_lan_v2.h"
@@ -54,6 +55,130 @@ class WifiLanV2Test : public ::testing::TestWithParam<FeatureFlags> {
MediumEnvironment& env_{MediumEnvironment::Instance()};
};
TEST_P(WifiLanV2Test, CanConnect) {
FeatureFlags feature_flags = GetParam();
env_.SetFeatureFlags(feature_flags);
env_.Start();
WifiLanV2 wifi_lan_client;
WifiLanV2 wifi_lan_server;
std::string service_id(kServiceID);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch accept_latch(1);
WifiLanSocketV2 socket_for_server;
EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
service_id,
{
.accepted_cb =
[&socket_for_server, &accept_latch](WifiLanSocketV2 socket) {
socket_for_server = std::move(socket);
accept_latch.CountDown();
},
}));
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
endpoint_info_name);
wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
NsdServiceInfo discovered_service_info;
wifi_lan_client.StartDiscovery(
service_id,
{
.service_discovered_cb =
[&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info, const std::string& service_id) {
NEARBY_LOGS(INFO)
<< "Discovered service_info=" << &service_info;
discovered_service_info = service_info;
discovered_latch.CountDown();
},
});
discovered_latch.Await(kWaitDuration).result();
ASSERT_TRUE(discovered_service_info.IsValid());
CancellationFlag flag;
WifiLanSocketV2 socket_for_client =
wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
EXPECT_TRUE(socket_for_server.IsValid());
EXPECT_TRUE(socket_for_client.IsValid());
env_.Stop();
}
TEST_P(WifiLanV2Test, CanCancelConnect) {
FeatureFlags feature_flags = GetParam();
env_.SetFeatureFlags(feature_flags);
env_.Start();
WifiLanV2 wifi_lan_client;
WifiLanV2 wifi_lan_server;
std::string service_id(kServiceID);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch accept_latch(1);
WifiLanSocketV2 socket_for_server;
EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
service_id,
{
.accepted_cb =
[&socket_for_server, &accept_latch](WifiLanSocketV2 socket) {
socket_for_server = std::move(socket);
accept_latch.CountDown();
},
}));
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
endpoint_info_name);
wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
NsdServiceInfo discovered_service_info;
wifi_lan_client.StartDiscovery(
service_id,
{
.service_discovered_cb =
[&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info, const std::string& service_id) {
NEARBY_LOGS(INFO)
<< "Discovered service_info=" << &service_info;
discovered_service_info = service_info;
discovered_latch.CountDown();
},
});
EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
ASSERT_TRUE(discovered_service_info.IsValid());
CancellationFlag flag(true);
WifiLanSocketV2 socket_for_client =
wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
// If FeatureFlag is disabled, Cancelled is false as no-op.
if (!feature_flags.enable_cancellation_flag) {
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
EXPECT_TRUE(socket_for_server.IsValid());
EXPECT_TRUE(socket_for_client.IsValid());
} else {
EXPECT_FALSE(accept_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_server.StopAcceptingConnections(service_id));
EXPECT_TRUE(wifi_lan_server.StopAdvertising(service_id));
EXPECT_FALSE(socket_for_server.IsValid());
EXPECT_FALSE(socket_for_client.IsValid());
}
env_.Stop();
}
INSTANTIATE_TEST_SUITE_P(ParametrisedWifiLanTest, WifiLanV2Test,
::testing::ValuesIn(kTestCases));
TEST_F(WifiLanV2Test, CanConstructValidObject) {
env_.Start();
WifiLanV2 wifi_lan_a;
@@ -72,6 +197,8 @@ TEST_F(WifiLanV2Test, CanStartAdvertising) {
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id, {}));
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
@@ -90,6 +217,9 @@ TEST_F(WifiLanV2Test, CanStartMultipleAdvertising) {
std::string service_info_name_2("ServiceInfoName_1");
std::string endpoint_info_name(kEndpointName);
EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id_1, {}));
EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id_2, {}));
NsdServiceInfo nsd_service_info_1;
nsd_service_info_1.SetServiceName(service_info_name_1);
nsd_service_info_1.SetTxtRecord(std::string(kEndpointInfoKey),
@@ -156,6 +286,8 @@ TEST_F(WifiLanV2Test, CanAdvertiseThatOtherMediumDiscover) {
},
});
EXPECT_TRUE(wifi_lan_a.StartAcceptingConnections(service_id, {}));
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
@@ -178,6 +310,8 @@ TEST_F(WifiLanV2Test, CanDiscoverThatOtherMediumAdvertise) {
CountDownLatch discovered_latch(1);
CountDownLatch lost_latch(1);
EXPECT_TRUE(wifi_lan_b.StartAcceptingConnections(service_id, {}));
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+149 -6
View File
@@ -28,6 +28,17 @@ namespace nearby {
namespace connections {
WifiLanV2::~WifiLanV2() {
// Destructor is not taking locks, but methods it is calling are.
while (!discovering_info_.service_ids.empty()) {
StopDiscovery(*discovering_info_.service_ids.begin());
}
while (!server_sockets_.empty()) {
StopAcceptingConnections(server_sockets_.begin()->first);
}
while (!advertising_info_.nsd_service_infos.empty()) {
StopAdvertising(advertising_info_.nsd_service_infos.begin()->first);
}
// All the AcceptLoopRunnable objects in here should already have gotten an
// opportunity to shut themselves down cleanly in the calls to
// StopAcceptingConnections() above.
@@ -46,6 +57,12 @@ bool WifiLanV2::StartAdvertising(const std::string& service_id,
NsdServiceInfo& nsd_service_info) {
MutexLock lock(&mutex_);
if (!IsAvailableLocked()) {
NEARBY_LOGS(INFO)
<< "Can't turn on WifiLan advertising. WifiLan is not available.";
return false;
}
if (!nsd_service_info.IsValid()) {
NEARBY_LOGS(INFO)
<< "Refusing to turn on WifiLan advertising. nsd_service_info is not "
@@ -59,13 +76,22 @@ bool WifiLanV2::StartAdvertising(const std::string& service_id,
return false;
}
if (!IsAvailableLocked()) {
if (!IsAcceptingConnectionsLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "Can't turn on WifiLan advertising. WifiLan is not available.";
<< "Failed to turn on WifiLan advertising with nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_id=" << service_id
<< ". Should accept connections before advertising.";
return false;
}
nsd_service_info.SetServiceType(GenerateServiceType(service_id));
const auto& it = server_sockets_.find(service_id);
if (it != server_sockets_.end()) {
nsd_service_info.SetIPAddress(it->second.GetIPAddress());
nsd_service_info.SetPort(it->second.GetPort());
}
if (!medium_.StartAdvertising(nsd_service_info)) {
NEARBY_LOGS(INFO)
<< "Failed to turn on WifiLan advertising with nsd_service_info="
@@ -179,12 +205,104 @@ bool WifiLanV2::IsDiscoveringLocked(const std::string& service_id) {
bool WifiLanV2::StartAcceptingConnections(const std::string& service_id,
AcceptedConnectionCallback callback) {
MutexLock lock(&mutex_);
return false;
if (service_id.empty()) {
NEARBY_LOGS(INFO) << "Refusing to start accepting WifiLan connections; "
"service_id is empty.";
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOGS(INFO)
<< "Can't start accepting WifiLan connections [service_id="
<< service_id << "]; WifiLan not available.";
return false;
}
if (IsAcceptingConnectionsLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "Refusing to start accepting WifiLan connections [service="
<< service_id
<< "]; WifiLan server is already in-progress with the same name.";
return false;
}
// We can generate an exact port here on server socket; now we just assign 0
// to let platform medium decide it.
int port = 0;
WifiLanServerSocketV2 server_socket = medium_.ListenForService(port);
if (!server_socket.IsValid()) {
NEARBY_LOGS(INFO)
<< "Failed to start accepting WifiLan connections for service_id="
<< service_id;
return false;
}
// Mark the fact that there's an in-progress WifiLan server accepting
// connections.
auto owned_server_socket =
server_sockets_.insert({service_id, std::move(server_socket)})
.first->second;
// Start the accept loop on a dedicated thread - this stays alive and
// listening for new incoming connections until StopAcceptingConnections() is
// invoked.
accept_loops_runner_.Execute(
"wifi-lan-accept",
[callback = std::move(callback),
server_socket = std::move(owned_server_socket), service_id]() mutable {
while (true) {
WifiLanSocketV2 client_socket = server_socket.Accept();
if (!client_socket.IsValid()) {
server_socket.Close();
break;
}
callback.accepted_cb(std::move(client_socket));
}
});
return true;
}
bool WifiLanV2::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_);
return false;
if (service_id.empty()) {
NEARBY_LOGS(INFO) << "Unable to stop accepting WifiLan connections because "
"the service_id is empty.";
return false;
}
const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) {
NEARBY_LOGS(INFO) << "Can't stop accepting WifiLan connections for "
<< service_id << " because it was never started.";
return false;
}
// Closing the WifiLanServerSocket will kick off the suicide of the thread
// in accept_loops_thread_pool_ that blocks on WifiLanServerSocket.accept().
// That may take some time to complete, but there's no particular reason to
// wait around for it.
auto item = server_sockets_.extract(it);
// Store a handle to the WifiLanServerSocket, so we can use it after
// removing the entry from server_sockets_; making it scoped
// is a bonus that takes care of deallocation before we leave this method.
WifiLanServerSocketV2& listening_socket = item.mapped();
// Regardless of whether or not we fail to close the existing
// WifiLanServerSocket, remove it from server_sockets_ so that it
// frees up this service for another round.
// Finally, close the WifiLanServerSocket.
if (!listening_socket.Close().Ok()) {
NEARBY_LOGS(INFO) << "Failed to close WifiLan server socket for service_id="
<< service_id;
return false;
}
return true;
}
bool WifiLanV2::IsAcceptingConnections(const std::string& service_id) {
@@ -200,8 +318,33 @@ WifiLanSocketV2 WifiLanV2::Connect(const std::string& service_id,
const NsdServiceInfo& service_info,
CancellationFlag* cancellation_flag) {
MutexLock lock(&mutex_);
// Socket to return. To allow for NRVO to work, it has to be a single object.
WifiLanSocketV2 socket;
return {};
if (service_id.empty()) {
NEARBY_LOGS(INFO) << "Refusing to create client WifiLan socket because "
"service_id is empty.";
return socket;
}
if (!IsAvailableLocked()) {
NEARBY_LOGS(INFO) << "Can't create client WifiLan socket [service_id="
<< service_id << "]; WifiLan isn't available.";
return socket;
}
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(INFO) << "Can't create client WifiLan socket due to cancel.";
return socket;
}
socket = medium_.ConnectToService(service_info, cancellation_flag);
if (!socket.IsValid()) {
NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
<< service_id << "]";
}
return socket;
}
WifiLanSocketV2 WifiLanV2::Connect(const std::string& service_id,
@@ -219,7 +362,7 @@ std::pair<std::string, int> WifiLanV2::GetCredentials(
if (it == server_sockets_.end()) {
return std::pair<std::string, int>();
}
return std::pair<std::string, int>(it->second.GetIpAddress(),
return std::pair<std::string, int>(it->second.GetIPAddress(),
it->second.GetPort());
}
+61 -19
View File
@@ -71,7 +71,7 @@ std::vector<proto::connections::Medium>
P2pClusterPcpHandler::GetConnectionMediumsByPriority() {
std::vector<proto::connections::Medium> mediums;
if (wifi_lan_medium_v2_.IsAvailable()) {
mediums.push_back(proto::connections::WIFI_LAN);
mediums.push_back(proto::connections::MDNS);
}
if (wifi_lan_medium_.IsAvailable()) {
mediums.push_back(proto::connections::WIFI_LAN);
@@ -100,7 +100,7 @@ BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartAdvertisingImpl(
WebRtcState web_rtc_state{WebRtcState::kUnconnectable};
if (options.allowed.wifi_lan) {
if (options.allowed.wifi_lan_v2) {
proto::connections::Medium wifi_lan_medium =
StartWifiLanV2Advertising(client, service_id, local_endpoint_id,
local_endpoint_info, web_rtc_state);
@@ -116,8 +116,8 @@ BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartAdvertisingImpl(
StartWifiLanAdvertising(client, service_id, local_endpoint_id,
local_endpoint_info, web_rtc_state);
if (wifi_lan_medium != proto::connections::UNKNOWN_MEDIUM) {
NEARBY_LOG(INFO,
"P2pClusterPcpHandler::StartAdvertisingImpl: WifiLan added");
NEARBY_LOGS(INFO)
<< "P2pClusterPcpHandler::StartAdvertisingImpl: WifiLan added";
mediums_started_successfully.push_back(wifi_lan_medium);
}
}
@@ -744,7 +744,7 @@ void P2pClusterPcpHandler::WifiLanV2ServiceDiscoveredHandler(
wifi_lan_service_info.GetEndpointId(),
wifi_lan_service_info.GetEndpointInfo(),
service_id,
proto::connections::Medium::WIFI_LAN,
proto::connections::Medium::MDNS,
wifi_lan_service_info.GetWebRtcState(),
},
service_info,
@@ -808,7 +808,7 @@ BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartDiscoveryImpl(
std::vector<proto::connections::Medium> mediums_started_successfully;
if (options.allowed.wifi_lan) {
if (options.allowed.wifi_lan_v2) {
proto::connections::Medium wifi_lan_medium = StartWifiLanV2Discovery(
{
.service_discovered_cb = absl::bind_front(
@@ -837,8 +837,8 @@ BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartDiscoveryImpl(
},
client, service_id);
if (wifi_lan_medium != proto::connections::UNKNOWN_MEDIUM) {
NEARBY_LOG(INFO,
"P2pClusterPcpHandler::StartDiscoveryImpl: WifiLan added");
NEARBY_LOGS(INFO)
<< "P2pClusterPcpHandler::StartDiscoveryImpl: WifiLan added";
mediums_started_successfully.push_back(wifi_lan_medium);
}
}
@@ -899,6 +899,7 @@ BasePcpHandler::StartOperationResult P2pClusterPcpHandler::StartDiscoveryImpl(
Status P2pClusterPcpHandler::StopDiscoveryImpl(ClientProxy* client) {
wifi_lan_medium_.StopDiscovery(client->GetDiscoveryServiceId());
wifi_lan_medium_v2_.StopDiscovery(client->GetDiscoveryServiceId());
if (client->GetClientId() == bluetooth_classic_discoverer_client_id_) {
bluetooth_medium_.StopDiscovery();
bluetooth_classic_discoverer_client_id_ = 0;
@@ -968,6 +969,13 @@ BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::ConnectImpl(
}
break;
}
case proto::connections::Medium::MDNS: {
auto* wifi_lan_endpoint = down_cast<WifiLanV2Endpoint*>(endpoint);
if (wifi_lan_endpoint) {
return WifiLanV2ConnectImpl(client, wifi_lan_endpoint);
}
break;
}
case proto::connections::Medium::WEB_RTC: {
break;
}
@@ -1531,8 +1539,9 @@ proto::connections::Medium P2pClusterPcpHandler::StartWifiLanV2Advertising(
<< service_id << ": start";
if (!wifi_lan_medium_v2_.IsAcceptingConnections(service_id)) {
if (!wifi_lan_medium_v2_.StartAcceptingConnections(
service_id, {.accepted_cb = [this, client, local_endpoint_info](
WifiLanSocketV2 socket) {
service_id,
{.accepted_cb = [this, client, local_endpoint_info,
local_endpoint_id](WifiLanSocketV2 socket) {
if (!socket.IsValid()) {
NEARBY_LOGS(WARNING)
<< "Invalid socket in accept callback("
@@ -1542,18 +1551,18 @@ proto::connections::Medium P2pClusterPcpHandler::StartWifiLanV2Advertising(
}
RunOnPcpHandlerThread(
"p2p-wifi-on-incoming-connection",
[this, client, local_endpoint_info,
[this, client, local_endpoint_id, local_endpoint_info,
socket = std::move(socket)]()
RUN_ON_PCP_HANDLER_THREAD() mutable {
std::string remote_service_info_name;
std::string remote_service_name = local_endpoint_id;
auto channel =
absl::make_unique<WifiLanEndpointChannelV2>(
remote_service_info_name, socket);
ByteArray remote_service_info{remote_service_info_name};
remote_service_name, socket);
ByteArray remote_service_name_byte{remote_service_name};
OnIncomingConnection(
client, remote_service_info, std::move(channel),
proto::connections::Medium::WIFI_LAN);
OnIncomingConnection(client, remote_service_name_byte,
std::move(channel),
proto::connections::Medium::MDNS);
});
}})) {
NEARBY_LOGS(WARNING)
@@ -1622,7 +1631,7 @@ proto::connections::Medium P2pClusterPcpHandler::StartWifiLanV2Advertising(
<< "), client=" << client->GetClientId()
<< " advertised with WifiLanServiceInfo "
<< nsd_service_info.GetServiceName();
return proto::connections::WIFI_LAN;
return proto::connections::MDNS;
}
proto::connections::Medium P2pClusterPcpHandler::StartWifiLanV2Discovery(
@@ -1633,7 +1642,7 @@ proto::connections::Medium P2pClusterPcpHandler::StartWifiLanV2Discovery(
<< client->GetClientId()
<< " started scanning for Wifi devices for service_id="
<< service_id;
return proto::connections::WIFI_LAN;
return proto::connections::MDNS;
} else {
NEARBY_LOGS(INFO) << "In StartWifiLanDiscovery(), client="
<< client->GetClientId()
@@ -1643,6 +1652,39 @@ proto::connections::Medium P2pClusterPcpHandler::StartWifiLanV2Discovery(
}
}
BasePcpHandler::ConnectImplResult P2pClusterPcpHandler::WifiLanV2ConnectImpl(
ClientProxy* client, WifiLanV2Endpoint* endpoint) {
NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
<< " is attempting to connect to endpoint(id="
<< endpoint->endpoint_id << ") over WifiLan.";
WifiLanSocketV2 socket = wifi_lan_medium_v2_.Connect(
endpoint->service_id, endpoint->service_info,
client->GetCancellationFlag(endpoint->endpoint_id));
NEARBY_LOGS(ERROR) << "In WifiLanConnectImpl(), connect to service "
<< " socket=" << &socket.GetImpl()
<< " for endpoint(id=" << endpoint->endpoint_id << ").";
if (!socket.IsValid()) {
NEARBY_LOGS(ERROR)
<< "In WifiLanConnectImpl(), failed to connect to service "
<< endpoint->service_info.GetServiceName()
<< " for endpoint(id=" << endpoint->endpoint_id << ").";
return BasePcpHandler::ConnectImplResult{
.status = {Status::kWifiLanError},
};
}
auto channel = absl::make_unique<WifiLanEndpointChannelV2>(
endpoint->endpoint_id, socket);
NEARBY_LOGS(INFO) << "Client " << client->GetClientId()
<< " created WifiLan endpoint channel to endpoint(id="
<< endpoint->endpoint_id << ").";
return BasePcpHandler::ConnectImplResult{
.medium = proto::connections::Medium::MDNS,
.status = {Status::kSuccess},
.endpoint_channel = std::move(channel),
};
}
} // namespace connections
} // namespace nearby
} // namespace location
@@ -207,6 +207,8 @@ class P2pClusterPcpHandler : public BasePcpHandler {
proto::connections::Medium StartWifiLanV2Discovery(
WifiLanV2DiscoveredServiceCallback callback, ClientProxy* client,
const std::string& service_id);
BasePcpHandler::ConnectImplResult WifiLanV2ConnectImpl(
ClientProxy* client, WifiLanV2Endpoint* endpoint);
BluetoothRadio& bluetooth_radio_;
BluetoothClassic& bluetooth_medium_;