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_;
+6 -2
View File
@@ -32,18 +32,19 @@ struct MediumSelector {
T ble;
T web_rtc;
T wifi_lan;
T wifi_lan_v2;
constexpr MediumSelector() = default;
constexpr MediumSelector(const MediumSelector&) = default;
constexpr MediumSelector& operator=(const MediumSelector&) = default;
constexpr bool Any(T value) const {
return bluetooth == value || ble == value || web_rtc == value ||
wifi_lan == value;
wifi_lan == value || wifi_lan_v2;
}
constexpr bool All(T value) const {
return bluetooth == value && ble == value && web_rtc == value &&
wifi_lan == value;
wifi_lan == value && wifi_lan_v2 == value;
}
constexpr int Count(T value) const {
@@ -51,6 +52,7 @@ struct MediumSelector {
if (bluetooth == value) count++;
if (ble == value) count++;
if (wifi_lan == value) count++;
if (wifi_lan_v2 == value) count++;
if (web_rtc == value) count++;
return count;
}
@@ -60,12 +62,14 @@ struct MediumSelector {
ble = value;
web_rtc = value;
wifi_lan = value;
wifi_lan_v2 = value;
return *this;
}
std::vector<Medium> GetMediums(T value) const {
std::vector<Medium> mediums;
// Mediums are sorted in order of decreasing preference.
if (wifi_lan_v2 == value) mediums.push_back(Medium::MDNS);
if (wifi_lan == value) mediums.push_back(Medium::WIFI_LAN);
if (web_rtc == value) mediums.push_back(Medium::WEB_RTC);
if (bluetooth == value) mediums.push_back(Medium::BLUETOOTH);
+3 -3
View File
@@ -54,10 +54,10 @@ class WifiLanServerSocketV2 {
virtual ~WifiLanServerSocketV2() = default;
// Returns ip address.
virtual std::string GetIpAddress() = 0;
virtual std::string GetIPAddress() const = 0;
// Returns port.
virtual int GetPort() = 0;
virtual int GetPort() const = 0;
// Blocks until either:
// - at least one incoming connection request is available, or
@@ -125,7 +125,7 @@ class WifiLanMediumV2 {
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
virtual std::unique_ptr<WifiLanSocketV2> ConnectToService(
NsdServiceInfo& remote_service_info,
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) = 0;
// Connects to a WifiLan service by ip address and port.
+17 -3
View File
@@ -268,10 +268,8 @@ void MediumEnvironment::OnWifiLanServiceV2StateChanged(
<< "; notify=" << enable_notifications_.load();
if (enabled) {
// Find advertising service with matched service_type. Report it as
// discovered by assigning the fake ip address and port.
// discovered.
NsdServiceInfo discovered_service_info(service_info);
discovered_service_info.SetIPAddress(GetFakeIPAddress());
discovered_service_info.SetPort(GetFakePort());
info.discovered_services.insert({service_type, discovered_service_info});
if (enable_notifications_) {
RunOnMediumEnvironmentThread(
@@ -862,6 +860,22 @@ void MediumEnvironment::UnregisterWifiLanMediumV2(
});
}
api::WifiLanMediumV2* MediumEnvironment::GetWifiLanV2Medium(
const std::string& ip_address, int port) {
for (auto& medium_info : wifi_lan_mediums_v2_) {
auto* medium_found = medium_info.first;
auto& info = medium_info.second;
for (auto& advertising_service : info.advertising_services) {
auto& service_info = advertising_service.second;
if (ip_address == service_info.GetIPAddress() &&
port == service_info.GetPort()) {
return medium_found;
}
}
}
return nullptr;
}
void MediumEnvironment::SetFeatureFlags(const FeatureFlags::Flags& flags) {
const_cast<FeatureFlags&>(FeatureFlags::GetInstance()).SetFlags(flags);
}
+4
View File
@@ -278,6 +278,10 @@ class MediumEnvironment {
// Removes medium-related info. This should correspond to device power off.
void UnregisterWifiLanMediumV2(api::WifiLanMediumV2& medium);
// Returns WiFi LAN service matching IP address and port, or nullptr.
api::WifiLanMediumV2* GetWifiLanV2Medium(const std::string& ip_address,
int port);
void SetFeatureFlags(const FeatureFlags::Flags& flags);
private:
+1
View File
@@ -74,6 +74,7 @@ cc_library(
"//absl/container:flat_hash_map",
"//absl/container:flat_hash_set",
"//absl/strings",
"//absl/strings:str_format",
"//absl/synchronization",
"//platform/api:comm",
"//platform/base",
+135 -18
View File
@@ -19,6 +19,8 @@
#include <string>
#include <utility>
#include "absl/strings/escaping.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "platform/api/wifi_lan_v2.h"
#include "platform/base/cancellation_flag_listener.h"
@@ -77,10 +79,8 @@ void WifiLanSocketV2::DoClose() {
remote_socket_ = nullptr;
output_->GetOutputStream().Close();
output_->GetInputStream().Close();
if (IsConnectedLocked()) {
input_->GetOutputStream().Close();
input_->GetInputStream().Close();
}
input_->GetOutputStream().Close();
input_->GetInputStream().Close();
closed_ = true;
}
}
@@ -97,28 +97,59 @@ OutputStream& WifiLanSocketV2::GetLocalOutputStream() {
return output_->GetOutputStream();
}
std::string WifiLanServerSocketV2::GetIpAddress() {
absl::MutexLock lock(&mutex_);
return {};
}
int WifiLanServerSocketV2::GetPort() {
absl::MutexLock lock(&mutex_);
return 0;
std::string WifiLanServerSocketV2::GetName(const std::string& ip_address,
int port) {
std::string dot_delimited_string;
if (!ip_address.empty()) {
for (auto byte : ip_address) {
if (!dot_delimited_string.empty())
absl::StrAppend(&dot_delimited_string, ".");
absl::StrAppend(&dot_delimited_string, absl::StrFormat("%d", byte));
}
}
std::string out = absl::StrCat(dot_delimited_string, ":", port);
return out;
}
std::unique_ptr<api::WifiLanSocketV2> WifiLanServerSocketV2::Accept() {
absl::MutexLock lock(&mutex_);
return nullptr;
while (!closed_ && pending_sockets_.empty()) {
cond_.Wait(&mutex_);
}
// whether or not we were running in the wait loop, return early if closed.
if (closed_) return {};
auto* remote_socket =
pending_sockets_.extract(pending_sockets_.begin()).value();
CHECK(remote_socket);
auto local_socket = std::make_unique<WifiLanSocketV2>();
local_socket->Connect(*remote_socket);
remote_socket->Connect(*local_socket);
cond_.SignalAll();
return local_socket;
}
bool WifiLanServerSocketV2::Connect(WifiLanSocketV2& socket) {
absl::MutexLock lock(&mutex_);
if (closed_) return false;
if (socket.IsConnected()) {
NEARBY_LOGS(ERROR)
<< "Failed to connect to WifiLan server socket: already connected";
return true; // already connected.
}
// add client socket to the pending list
pending_sockets_.insert(&socket);
cond_.SignalAll();
while (!socket.IsConnected()) {
cond_.Wait(&mutex_);
if (closed_) return false;
}
return true;
}
void WifiLanServerSocketV2::SetCloseNotifier(std::function<void()> notifier) {
absl::MutexLock lock(&mutex_);
close_notifier_ = std::move(notifier);
}
WifiLanServerSocketV2::~WifiLanServerSocketV2() {
@@ -131,7 +162,22 @@ Exception WifiLanServerSocketV2::Close() {
return DoClose();
}
Exception WifiLanServerSocketV2::DoClose() { return {Exception::kSuccess}; }
Exception WifiLanServerSocketV2::DoClose() {
bool should_notify = !closed_;
closed_ = true;
if (should_notify) {
cond_.SignalAll();
if (close_notifier_) {
auto notifier = std::move(close_notifier_);
mutex_.Unlock();
// Notifier may contain calls to public API, and may cause deadlock, if
// mutex_ is held during the call.
notifier();
mutex_.Lock();
}
}
return {Exception::kSuccess};
}
WifiLanMediumV2::WifiLanMediumV2() {
auto& env = MediumEnvironment::Instance();
@@ -235,19 +281,90 @@ bool WifiLanMediumV2::StopDiscovery(const std::string& service_type) {
}
std::unique_ptr<api::WifiLanSocketV2> WifiLanMediumV2::ConnectToService(
NsdServiceInfo& remote_service_info, CancellationFlag* cancellation_flag) {
return nullptr;
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) {
std::string service_type = remote_service_info.GetServiceType();
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", service_type=" << service_type;
return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag);
}
std::unique_ptr<api::WifiLanSocketV2> WifiLanMediumV2::ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
return nullptr;
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", ip address + port="
<< WifiLanServerSocketV2::GetName(ip_address, port);
// First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance();
auto* remote_medium =
static_cast<WifiLanMediumV2*>(env.GetWifiLanV2Medium(ip_address, port));
if (!remote_medium) {
return {};
}
WifiLanServerSocketV2* server_socket = nullptr;
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService [peer]: medium="
<< remote_medium << ", remote ip address + port="
<< WifiLanServerSocketV2::GetName(ip_address, port);
// Then, find our server socket context in this medium.
std::string socket_name = WifiLanServerSocketV2::GetName(ip_address, port);
{
absl::MutexLock medium_lock(&remote_medium->mutex_);
auto item = remote_medium->server_sockets_.find(socket_name);
server_socket = item != server_sockets_.end() ? item->second : nullptr;
if (server_socket == nullptr) {
NEARBY_LOGS(ERROR)
<< "G3 WifiLan Failed to find WifiLan Server socket: socket_name="
<< socket_name;
return {};
}
}
if (cancellation_flag->Cancelled()) {
NEARBY_LOGS(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name="
<< socket_name;
return {};
}
CancellationFlagListener listener(cancellation_flag, [&server_socket]() {
NEARBY_LOGS(INFO) << "G3 WifiLan Cancel Connect.";
if (server_socket != nullptr) {
server_socket->Close();
}
});
auto socket = std::make_unique<WifiLanSocketV2>();
// Finally, Request to connect to this socket.
if (!server_socket->Connect(*socket)) {
NEARBY_LOGS(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan "
"Server socket: name="
<< socket_name;
return {};
}
NEARBY_LOGS(INFO) << "G3 WifiLan ConnectToService: connected: socket="
<< socket.get();
return socket;
}
std::unique_ptr<api::WifiLanServerSocketV2> WifiLanMediumV2::ListenForService(
int port) {
return {};
auto& env = MediumEnvironment::Instance();
auto server_socket = std::make_unique<WifiLanServerSocketV2>();
server_socket->SetIPAddress(env.GetFakeIPAddress());
server_socket->SetPort(port == 0 ? env.GetFakePort() : port);
std::string socket_name = WifiLanServerSocketV2::GetName(
server_socket->GetIPAddress(), server_socket->GetPort());
server_socket->SetCloseNotifier([this, socket_name]() {
absl::MutexLock lock(&mutex_);
server_sockets_.erase(socket_name);
});
NEARBY_LOGS(INFO) << "G3 WifiLan Adding server socket: medium=" << this
<< ", socket_name=" << socket_name;
absl::MutexLock lock(&mutex_);
server_sockets_.insert({socket_name, server_socket.get()});
return server_socket;
}
} // namespace g3
+35 -6
View File
@@ -92,13 +92,33 @@ class WifiLanSocketV2 : public api::WifiLanSocketV2 {
class WifiLanServerSocketV2 : public api::WifiLanServerSocketV2 {
public:
static std::string GetName(const std::string& ip_address, int port);
~WifiLanServerSocketV2() override;
// Returns ip address.
std::string GetIpAddress() override ABSL_LOCKS_EXCLUDED(mutex_);
// Gets ip address.
std::string GetIPAddress() const override ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
return ip_address_;
}
// Returns port.
int GetPort() override ABSL_LOCKS_EXCLUDED(mutex_);
// Sets the ip address.
void SetIPAddress(const std::string& ip_address) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
ip_address_ = ip_address;
}
// Gets the port.
int GetPort() const override ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
return port_;
}
// Sets the port.
void SetPort(int port) ABSL_LOCKS_EXCLUDED(mutex_) {
absl::MutexLock lock(&mutex_);
port_ = port;
}
// Blocks until either:
// - at least one incoming connection request is available, or
@@ -135,7 +155,14 @@ class WifiLanServerSocketV2 : public api::WifiLanServerSocketV2 {
private:
Exception DoClose() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
absl::Mutex mutex_;
mutable absl::Mutex mutex_;
std::string ip_address_ ABSL_GUARDED_BY(mutex_);
int port_ ABSL_GUARDED_BY(mutex_);
absl::CondVar cond_;
absl::flat_hash_set<WifiLanSocketV2*> pending_sockets_
ABSL_GUARDED_BY(mutex_);
std::function<void()> close_notifier_ ABSL_GUARDED_BY(mutex_);
bool closed_ ABSL_GUARDED_BY(mutex_) = false;
};
// Container of operations that can be performed over the WifiLan medium.
@@ -187,7 +214,7 @@ class WifiLanMediumV2 : public api::WifiLanMediumV2 {
// On success, returns a new WifiLanSocket.
// On error, returns nullptr.
std::unique_ptr<api::WifiLanSocketV2> ConnectToService(
NsdServiceInfo& remote_service_info,
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) override;
// Connects to a WifiLan service by ip address and port.
@@ -242,6 +269,8 @@ class WifiLanMediumV2 : public api::WifiLanMediumV2 {
absl::Mutex mutex_;
AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
absl::flat_hash_map<std::string, WifiLanServerSocketV2*> server_sockets_
ABSL_GUARDED_BY(mutex_);
};
} // namespace g3
+165
View File
@@ -53,6 +53,159 @@ class WifiLanMediumV2Test : public ::testing::TestWithParam<FeatureFlags> {
MediumEnvironment& env_{MediumEnvironment::Instance()};
};
TEST_P(WifiLanMediumV2Test, CanConnectToService) {
FeatureFlags feature_flags = GetParam();
env_.SetFeatureFlags(feature_flags);
env_.Start();
WifiLanMediumV2 wifi_lan_a;
WifiLanMediumV2 wifi_lan_b;
std::string service_id(kServiceId);
std::string service_type(kServiceType);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch lost_latch(1);
WifiLanServerSocketV2 server_socket = wifi_lan_b.ListenForService();
EXPECT_TRUE(server_socket.IsValid());
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
endpoint_info_name);
nsd_service_info.SetServiceType(service_type);
nsd_service_info.SetIPAddress(server_socket.GetIPAddress());
nsd_service_info.SetPort(server_socket.GetPort());
wifi_lan_b.StartAdvertising(nsd_service_info);
NsdServiceInfo discovered_service_info;
wifi_lan_a.StartDiscovery(
service_id, service_type,
DiscoveredServiceCallback{
.service_discovered_cb =
[&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info,
const std::string& service_type) {
discovered_service_info = service_info;
discovered_latch.CountDown();
},
.service_lost_cb =
[&lost_latch](NsdServiceInfo service_info,
const std::string& service_type) {
lost_latch.CountDown();
},
});
EXPECT_TRUE(discovered_latch.Await(absl::Milliseconds(1000)).result());
WifiLanSocketV2 socket_a;
WifiLanSocketV2 socket_b;
EXPECT_FALSE(socket_a.IsValid());
EXPECT_FALSE(socket_b.IsValid());
{
CancellationFlag flag;
SingleThreadExecutor server_executor;
SingleThreadExecutor client_executor;
client_executor.Execute([&wifi_lan_a, &socket_a,
discovered_service_info = discovered_service_info,
service_type, &server_socket, &flag]() {
socket_a = wifi_lan_a.ConnectToService(discovered_service_info, &flag);
if (!socket_a.IsValid()) {
server_socket.Close();
}
});
server_executor.Execute([&socket_b, &server_socket]() {
socket_b = server_socket.Accept();
if (!socket_b.IsValid()) {
server_socket.Close();
}
});
}
EXPECT_TRUE(socket_a.IsValid());
EXPECT_TRUE(socket_b.IsValid());
server_socket.Close();
env_.Stop();
}
TEST_P(WifiLanMediumV2Test, CanCancelConnect) {
FeatureFlags feature_flags = GetParam();
env_.SetFeatureFlags(feature_flags);
env_.Start();
WifiLanMediumV2 wifi_lan_a;
WifiLanMediumV2 wifi_lan_b;
std::string service_id(kServiceId);
std::string service_type(kServiceType);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch lost_latch(1);
WifiLanServerSocketV2 server_socket = wifi_lan_b.ListenForService();
EXPECT_TRUE(server_socket.IsValid());
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
endpoint_info_name);
nsd_service_info.SetServiceType(service_type);
nsd_service_info.SetIPAddress(server_socket.GetIPAddress());
nsd_service_info.SetPort(server_socket.GetPort());
wifi_lan_b.StartAdvertising(nsd_service_info);
NsdServiceInfo discovered_service_info;
wifi_lan_a.StartDiscovery(
service_id, service_type,
DiscoveredServiceCallback{
.service_discovered_cb =
[&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info,
const std::string& service_type) {
discovered_service_info = service_info;
discovered_latch.CountDown();
},
.service_lost_cb =
[&lost_latch](NsdServiceInfo service_info,
const std::string& service_type) {
lost_latch.CountDown();
},
});
EXPECT_TRUE(discovered_latch.Await(absl::Milliseconds(1000)).result());
WifiLanSocketV2 socket_a;
WifiLanSocketV2 socket_b;
EXPECT_FALSE(socket_a.IsValid());
EXPECT_FALSE(socket_b.IsValid());
{
CancellationFlag flag(true);
SingleThreadExecutor server_executor;
SingleThreadExecutor client_executor;
client_executor.Execute([&wifi_lan_a, &socket_a,
discovered_service_info = discovered_service_info,
service_type, &server_socket, &flag]() {
socket_a = wifi_lan_a.ConnectToService(discovered_service_info, &flag);
if (!socket_a.IsValid()) {
server_socket.Close();
}
});
server_executor.Execute([&socket_b, &server_socket]() {
socket_b = server_socket.Accept();
if (!socket_b.IsValid()) {
server_socket.Close();
}
});
}
// If FeatureFlag is disabled, Cancelled is false as no-op.
if (!feature_flags.enable_cancellation_flag) {
EXPECT_TRUE(socket_a.IsValid());
EXPECT_TRUE(socket_b.IsValid());
} else {
EXPECT_FALSE(socket_a.IsValid());
EXPECT_FALSE(socket_b.IsValid());
}
server_socket.Close();
env_.Stop();
}
INSTANTIATE_TEST_SUITE_P(ParametrisedWifiLanMediumTest, WifiLanMediumV2Test,
::testing::ValuesIn(kTestCases));
TEST_F(WifiLanMediumV2Test, ConstructorDestructorWorks) {
env_.Start();
WifiLanMediumV2 wifi_lan_a;
@@ -74,6 +227,9 @@ TEST_F(WifiLanMediumV2Test, CanStartAdvertising) {
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
WifiLanServerSocketV2 server_socket = wifi_lan_a.ListenForService();
EXPECT_TRUE(server_socket.IsValid());
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
@@ -93,6 +249,9 @@ TEST_F(WifiLanMediumV2Test, CanStartMultipleAdvertising) {
std::string service_info_name_2(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
WifiLanServerSocketV2 server_socket = wifi_lan_a.ListenForService();
EXPECT_TRUE(server_socket.IsValid());
NsdServiceInfo nsd_service_info_1;
nsd_service_info_1.SetServiceName(service_info_name_1);
nsd_service_info_1.SetTxtRecord(std::string(kEndpointInfoKey),
@@ -167,6 +326,9 @@ TEST_F(WifiLanMediumV2Test, CanAdvertiseThatOtherMediumDiscover) {
},
});
WifiLanServerSocketV2 server_socket = wifi_lan_a.ListenForService();
EXPECT_TRUE(server_socket.IsValid());
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
@@ -206,6 +368,9 @@ TEST_F(WifiLanMediumV2Test, CanDiscoverThatOtherMediumAdvertise) {
},
});
WifiLanServerSocketV2 server_socket = wifi_lan_a.ListenForService();
EXPECT_TRUE(server_socket.IsValid());
NsdServiceInfo nsd_service_info;
nsd_service_info.SetServiceName(service_info_name);
nsd_service_info.SetTxtRecord(std::string(kEndpointInfoKey),
+10 -3
View File
@@ -125,14 +125,21 @@ bool WifiLanMediumV2::StopDiscovery(const std::string& service_type) {
}
WifiLanSocketV2 WifiLanMediumV2::ConnectToService(
NsdServiceInfo remote_service_info, CancellationFlag* cancellation_flag) {
return {};
const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) {
NEARBY_LOGS(INFO) << "WifiLanMedium::ConnectToService: remote_service_name="
<< remote_service_info.GetServiceName();
return WifiLanSocketV2(
impl_->ConnectToService(remote_service_info, cancellation_flag));
}
WifiLanSocketV2 WifiLanMediumV2::ConnectToService(
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
return {};
NEARBY_LOGS(INFO) << "WifiLanMedium::ConnectToService: ip address="
<< ip_address << ", port=" << port;
return WifiLanSocketV2(
impl_->ConnectToService(ip_address, port, cancellation_flag));
}
} // namespace nearby
+3 -3
View File
@@ -88,7 +88,7 @@ class WifiLanServerSocketV2 final {
: impl_(std::move(socket)) {}
// Returns ip address.
std::string GetIpAddress() { return impl_->GetIpAddress(); }
std::string GetIPAddress() { return impl_->GetIPAddress(); }
// Returns port.
int GetPort() { return impl_->GetPort(); }
@@ -174,7 +174,7 @@ class WifiLanMediumV2 {
// Returns a new WifiLanSocket.
// On Success, WifiLanSocket::IsValid() returns true.
WifiLanSocketV2 ConnectToService(NsdServiceInfo remote_service_info,
WifiLanSocketV2 ConnectToService(const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag);
// Returns a new WifiLanSocket by ip address and port.
@@ -184,7 +184,7 @@ class WifiLanMediumV2 {
// Returns a new WifiLanServerSocket.
// On Success, WifiLanServerSocket::IsValid() returns true.
WifiLanServerSocketV2 ListenForService(int port) {
WifiLanServerSocketV2 ListenForService(int port = 0) {
return WifiLanServerSocketV2(impl_->ListenForService(port));
}