nearbyconnections : Replace WifiLanV2 to WifiLan.

PiperOrigin-RevId: 406033177
This commit is contained in:
edwinwu
2021-10-27 18:59:43 -07:00
committed by Copybara-Service
parent 94ef1b532b
commit acf516189b
43 changed files with 1353 additions and 4555 deletions
-3
View File
@@ -24,7 +24,6 @@ cc_library(
"uuid.cc",
"webrtc.cc",
"wifi_lan.cc",
"wifi_lan_v2.cc",
],
hdrs = [
"ble.h",
@@ -36,7 +35,6 @@ cc_library(
"uuid.h",
"webrtc.h",
"wifi_lan.h",
"wifi_lan_v2.h",
],
compatible_with = ["//buildenv/target:non_prod"],
visibility = [
@@ -104,7 +102,6 @@ cc_test(
"lost_entity_tracker_test.cc",
"uuid_test.cc",
"wifi_lan_test.cc",
"wifi_lan_test_v2.cc",
],
shard_count = 16,
deps = [
-2
View File
@@ -26,8 +26,6 @@ Ble& Mediums::GetBle() { return ble_; }
WifiLan& Mediums::GetWifiLan() { return wifi_lan_; }
WifiLanV2& Mediums::GetWifiLanV2() { return wifi_lan_v2_; }
mediums::WebRtc& Mediums::GetWebRtc() { return webrtc_; }
} // namespace connections
-5
View File
@@ -20,7 +20,6 @@
#include "core/internal/mediums/bluetooth_radio.h"
#include "core/internal/mediums/webrtc.h"
#include "core/internal/mediums/wifi_lan.h"
#include "core/internal/mediums/wifi_lan_v2.h"
namespace location {
namespace nearby {
@@ -44,9 +43,6 @@ class Mediums {
// Returns a handle to the Wifi-Lan medium.
WifiLan& GetWifiLan();
// Returns a handle to the Wifi-Lan medium.
WifiLanV2& GetWifiLanV2();
// Returns a handle to the WebRtc medium.
mediums::WebRtc& GetWebRtc();
@@ -63,7 +59,6 @@ class Mediums {
BluetoothClassic bluetooth_classic_{bluetooth_radio_};
Ble ble_{bluetooth_radio_};
WifiLan wifi_lan_;
WifiLanV2 wifi_lan_v2_;
mediums::WebRtc webrtc_;
};
+190 -81
View File
@@ -27,6 +27,24 @@ namespace location {
namespace nearby {
namespace connections {
WifiLan::~WifiLan() {
// 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.
accept_loops_runner_.Shutdown();
}
bool WifiLan::IsAvailable() const {
MutexLock lock(&mutex_);
@@ -39,6 +57,12 @@ bool WifiLan::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 "
@@ -52,27 +76,36 @@ bool WifiLan::StartAdvertising(const std::string& service_id,
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(INFO,
"Can't turn on WifiLan advertising. WifiLan is not available.");
if (!IsAcceptingConnectionsLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "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));
if (!medium_.StartAdvertising(service_id, nsd_service_info)) {
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 wifi_lan_service="
<< "Failed to turn on WifiLan advertising with nsd_service_info="
<< &nsd_service_info
<< ", service_info_name=" << nsd_service_info.GetServiceName()
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_id=" << service_id;
return false;
}
NEARBY_LOGS(INFO) << "Turned on WifiLan advertising with wifi_lan_service="
<< &nsd_service_info << ", service_info_name="
<< nsd_service_info.GetServiceName()
NEARBY_LOGS(INFO) << "Turned on WifiLan advertising with nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_id=" << service_id;
advertising_info_.Add(service_id);
advertising_info_.Add(service_id, std::move(nsd_service_info));
return true;
}
@@ -80,15 +113,17 @@ bool WifiLan::StopAdvertising(const std::string& service_id) {
MutexLock lock(&mutex_);
if (!IsAdvertisingLocked(service_id)) {
NEARBY_LOG(INFO, "Can't turn off WifiLan advertising; it is already off");
NEARBY_LOGS(INFO)
<< "Can't turn off WifiLan advertising; it is already off";
return false;
}
NEARBY_LOG(INFO, "Turned off WifiLan advertising with service_id=%s",
service_id.c_str());
bool ret = medium_.StopAdvertising(service_id);
NEARBY_LOGS(INFO) << "Turned off WifiLan advertising with service_id="
<< service_id;
bool ret =
medium_.StopAdvertising(*advertising_info_.GetServiceInfo(service_id));
// Reset our bundle of advertising state to mark that we're no longer
// advertising.
// advertising for specific service_id.
advertising_info_.Remove(service_id);
return ret;
}
@@ -108,33 +143,33 @@ bool WifiLan::StartDiscovery(const std::string& service_id,
MutexLock lock(&mutex_);
if (service_id.empty()) {
NEARBY_LOG(INFO,
"Refusing to start WifiLan discovering with empty service_id.");
NEARBY_LOGS(INFO)
<< "Refusing to start WifiLan discovering with empty service_id.";
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(
INFO,
"Can't discover WifiLan services because WifiLan isn't available.");
NEARBY_LOGS(INFO)
<< "Can't discover WifiLan services because WifiLan isn't available.";
return false;
}
if (IsDiscoveringLocked(service_id)) {
NEARBY_LOG(
INFO,
"Refusing to start discovery of WifiLan services because another "
"discovery is already in-progress.");
NEARBY_LOGS(INFO)
<< "Refusing to start discovery of WifiLan services because another "
"discovery is already in-progress.";
return false;
}
if (!medium_.StartDiscovery(service_id, callback)) {
NEARBY_LOG(INFO, "Failed to start discovery of WifiLan services.");
std::string service_type = GenerateServiceType(service_id);
bool ret = medium_.StartDiscovery(service_id, service_type, callback);
if (!ret) {
NEARBY_LOGS(INFO) << "Failed to start discovery of WifiLan services.";
return false;
}
NEARBY_LOG(INFO, "Turned on WifiLan discovering with service_id=%s",
service_id.c_str());
NEARBY_LOGS(INFO) << "Turned on WifiLan discovering with service_id="
<< service_id;
// Mark the fact that we're currently performing a WifiLan discovering.
discovering_info_.Add(service_id);
return true;
@@ -144,22 +179,22 @@ bool WifiLan::StopDiscovery(const std::string& service_id) {
MutexLock lock(&mutex_);
if (!IsDiscoveringLocked(service_id)) {
NEARBY_LOG(INFO,
"Can't turn off WifiLan discovering because we never started "
"discovering.");
NEARBY_LOGS(INFO)
<< "Can't turn off WifiLan discovering because we never started "
"discovering.";
return false;
}
NEARBY_LOG(INFO, "Turned off WifiLan discovering with service_id=%s",
service_id.c_str());
bool ret = medium_.StopDiscovery(service_id);
discovering_info_.Clear();
std::string service_type = GenerateServiceType(service_id);
NEARBY_LOGS(INFO) << "Turned off WifiLan discovering with service_id="
<< service_id << ", service_type=" << service_type;
bool ret = medium_.StopDiscovery(service_type);
discovering_info_.Remove(service_id);
return ret;
}
bool WifiLan::IsDiscovering(const std::string& service_id) {
MutexLock lock(&mutex_);
return IsDiscoveringLocked(service_id);
}
@@ -172,87 +207,129 @@ bool WifiLan::StartAcceptingConnections(const std::string& service_id,
MutexLock lock(&mutex_);
if (service_id.empty()) {
NEARBY_LOG(INFO,
"Refusing to start accepting WifiLan connections with empty "
"service_id.");
NEARBY_LOGS(INFO) << "Refusing to start accepting WifiLan connections; "
"service_id is empty.";
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(INFO,
"Can't start accepting WifiLan connections for %s because "
"WifiLan isn't available.",
service_id.c_str());
NEARBY_LOGS(INFO)
<< "Can't start accepting WifiLan connections [service_id="
<< service_id << "]; WifiLan not available.";
return false;
}
if (IsAcceptingConnectionsLocked(service_id)) {
NEARBY_LOG(INFO,
"Refusing to start accepting WifiLan connections for %s because "
"another WifiLan service socket is already in-progress.",
service_id.c_str());
NEARBY_LOGS(INFO)
<< "Refusing to start accepting WifiLan connections [service="
<< service_id
<< "]; WifiLan server is already in-progress with the same name.";
return false;
}
if (!medium_.StartAcceptingConnections(service_id, callback)) {
NEARBY_LOG(INFO, "Failed to accept connections callback for %s.",
service_id.c_str());
// We can generate an exact port here on server socket; now we just assign 0
// to let platform medium decide it.
int port = 0;
WifiLanServerSocket 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;
}
accepting_connections_info_.Add(service_id);
// 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) {
WifiLanSocket client_socket = server_socket.Accept();
if (!client_socket.IsValid()) {
server_socket.Close();
break;
}
callback.accepted_cb(std::move(client_socket));
}
});
return true;
}
bool WifiLan::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_);
if (!IsAcceptingConnectionsLocked(service_id)) {
NEARBY_LOG(INFO,
"Can't stop accepting WifiLan connections because it was never "
"started.");
if (service_id.empty()) {
NEARBY_LOGS(INFO) << "Unable to stop accepting WifiLan connections because "
"the service_id is empty.";
return false;
}
bool ret = medium_.StopAcceptingConnections(service_id);
// Reset our bundle of accepting connections state to mark that we're no
// longer accepting connections.
accepting_connections_info_.Remove(service_id);
return ret;
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.
WifiLanServerSocket& 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 WifiLan::IsAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_);
return IsAcceptingConnectionsLocked(service_id);
}
bool WifiLan::IsAcceptingConnectionsLocked(const std::string& service_id) {
return accepting_connections_info_.Existed(service_id);
return server_sockets_.find(service_id) != server_sockets_.end();
}
WifiLanSocket WifiLan::Connect(WifiLanService& wifi_lan_service,
const std::string& service_id,
WifiLanSocket WifiLan::Connect(const std::string& service_id,
const NsdServiceInfo& service_info,
CancellationFlag* cancellation_flag) {
MutexLock lock(&mutex_);
NEARBY_LOGS(INFO) << "WifiLan::Connect: wifi_lan_service="
<< &wifi_lan_service << ", service_info_name="
<< wifi_lan_service.GetServiceInfo().GetServiceName()
<< ", service_id=" << service_id;
// Socket to return. To allow for NRVO to work, it has to be a single object.
WifiLanSocket socket;
if (service_id.empty()) {
NEARBY_LOG(INFO,
"Refusing to create WifiLan socket with empty service_id.");
NEARBY_LOGS(INFO) << "Refusing to create client WifiLan socket because "
"service_id is empty.";
return socket;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(INFO,
"Can't create client WifiLan socket [service_id=%s]; WifiLan "
"isn't available.",
service_id.c_str());
NEARBY_LOGS(INFO) << "Can't create client WifiLan socket [service_id="
<< service_id << "]; WifiLan isn't available.";
return socket;
}
@@ -261,25 +338,57 @@ WifiLanSocket WifiLan::Connect(WifiLanService& wifi_lan_service,
return socket;
}
socket = medium_.Connect(wifi_lan_service, service_id, cancellation_flag);
socket = medium_.ConnectToService(service_info, cancellation_flag);
if (!socket.IsValid()) {
NEARBY_LOG(INFO, "Failed to Connect via WifiLan [service_id=%s]",
service_id.c_str());
NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
<< service_id << "]";
}
return socket;
}
WifiLanService WifiLan::GetRemoteWifiLanService(const std::string& ip_address,
int port) {
WifiLanSocket WifiLan::Connect(const std::string& service_id,
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
MutexLock lock(&mutex_);
return medium_.GetRemoteService(ip_address, port);
// Socket to return. To allow for NRVO to work, it has to be a single object.
WifiLanSocket socket;
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(ip_address, port, cancellation_flag);
if (!socket.IsValid()) {
NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
<< service_id << "]";
}
return socket;
}
std::pair<std::string, int> WifiLan::GetCredentials(
const std::string& service_id) {
MutexLock lock(&mutex_);
return medium_.GetCredentials(service_id);
const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) {
return std::pair<std::string, int>();
}
return std::pair<std::string, int>(it->second.GetIPAddress(),
it->second.GetPort());
}
std::string WifiLan::GenerateServiceType(const std::string& service_id) {
+60 -33
View File
@@ -22,6 +22,7 @@
#include "absl/container/flat_hash_set.h"
#include "platform/base/byte_array.h"
#include "platform/base/cancellation_flag.h"
#include "platform/base/nsd_service_info.h"
#include "platform/public/multi_thread_executor.h"
#include "platform/public/mutex.h"
#include "platform/public/wifi_lan.h"
@@ -33,33 +34,42 @@ namespace connections {
class WifiLan {
public:
using DiscoveredServiceCallback = WifiLanMedium::DiscoveredServiceCallback;
using AcceptedConnectionCallback = WifiLanMedium::AcceptedConnectionCallback;
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(WifiLanSocket socket)> accepted_cb =
DefaultCallback<WifiLanSocket>();
};
WifiLan() = default;
~WifiLan();
// Returns true, if WifiLan communications are supported by a platform.
bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
// Sets custom service info name, endpoint info name in NsdServiceInfo and
// then enables WifiLan advertising.
// Returns true, if name is successfully set, and false otherwise.
// Returns true, if NsdServiceInfo is successfully set, and false otherwise.
bool StartAdvertising(const std::string& service_id,
NsdServiceInfo& nsd_service_info)
ABSL_LOCKS_EXCLUDED(mutex_);
// Disables WifiLan advertising, and restores service info name to
// what they were before the call to StartAdvertising().
// Disables WifiLan advertising.
// Returns false if no successful call StartAdvertising() was previously
// made, otherwise returns true.
bool StopAdvertising(const std::string& service_id)
ABSL_LOCKS_EXCLUDED(mutex_);
bool IsAdvertising(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
// Enables WifiLan discovery mode. Will report any discoverable services in
// range through a callback. Returns true, if discovery mode was enabled,
// false otherwise.
// Enables WifiLan discovery. Will report any discoverable services
// through a callback.
// Returns true, if discovery was enabled, false otherwise.
bool StartDiscovery(const std::string& service_id,
DiscoveredServiceCallback callback)
ABSL_LOCKS_EXCLUDED(mutex_);
// Disables WifiLan discovery mode.
// Disables WifiLan discovery.
bool StopDiscovery(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
bool IsDiscovering(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
@@ -81,36 +91,55 @@ class WifiLan {
// another service with StartAcceptingConnections() using the same service_id.
// Blocks until connection is established, or server-side is terminated.
// Returns socket instance. On success, WifiLanSocket.IsValid() return true.
WifiLanSocket Connect(WifiLanService& wifi_lan_service,
const std::string& service_id,
WifiLanSocket Connect(const std::string& service_id,
const NsdServiceInfo& service_info,
CancellationFlag* cancellation_flag)
ABSL_LOCKS_EXCLUDED(mutex_);
WifiLanService GetRemoteWifiLanService(const std::string& ip_address,
int port) ABSL_LOCKS_EXCLUDED(mutex_);
// Establishes connection to WifiLan service by ip address and port for
// bandwidth upgradation.
// Returns socket instance. On success, WifiLanSocket.IsValid() return true.
WifiLanSocket Connect(const std::string& service_id,
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag)
ABSL_LOCKS_EXCLUDED(mutex_);
// Gets ip address + port for remote services on the network to identify and
// connect to this service.
//
// Credential is for the currently-hosted Wifi ServerSocket (if any).
std::pair<std::string, int> GetCredentials(const std::string& service_id)
ABSL_LOCKS_EXCLUDED(mutex_);
private:
struct AdvertisingInfo {
bool Empty() const { return service_ids.empty(); }
void Clear() { service_ids.clear(); }
void Add(const std::string& service_id) { service_ids.emplace(service_id); }
bool Empty() const { return nsd_service_infos.empty(); }
void Clear() { nsd_service_infos.clear(); }
void Add(const std::string& service_id,
const NsdServiceInfo& nsd_service_info) {
nsd_service_infos.insert({service_id, nsd_service_info});
}
void Remove(const std::string& service_id) {
service_ids.erase(service_id);
nsd_service_infos.erase(service_id);
}
bool Existed(const std::string& service_id) const {
return service_ids.contains(service_id);
return nsd_service_infos.contains(service_id);
}
NsdServiceInfo* GetServiceInfo(const std::string& service_id) {
const auto& it = nsd_service_infos.find(service_id);
if (it == nsd_service_infos.end()) {
return nullptr;
}
return &it->second;
}
absl::flat_hash_set<std::string> service_ids;
absl::flat_hash_map<std::string, NsdServiceInfo> nsd_service_infos;
};
struct DiscoveringInfo {
bool Empty() const { return service_ids.empty(); }
void Clear() { service_ids.clear(); }
void Add(const std::string& service_id) { service_ids.emplace(service_id); }
void Add(const std::string& service_id) { service_ids.insert(service_id); }
void Remove(const std::string& service_id) {
service_ids.erase(service_id);
}
@@ -121,19 +150,7 @@ class WifiLan {
absl::flat_hash_set<std::string> service_ids;
};
struct AcceptingConnectionsInfo {
bool Empty() const { return service_ids.empty(); }
void Clear() { service_ids.clear(); }
void Add(const std::string& service_id) { service_ids.emplace(service_id); }
void Remove(const std::string& service_id) {
service_ids.erase(service_id);
}
bool Existed(const std::string& service_id) const {
return service_ids.contains(service_id);
}
absl::flat_hash_set<std::string> service_ids;
};
static constexpr int kMaxConcurrentAcceptLoops = 5;
// Same as IsAvailable(), but must be called with mutex_ held.
bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
@@ -157,7 +174,17 @@ class WifiLan {
WifiLanMedium medium_ ABSL_GUARDED_BY(mutex_);
AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
AcceptingConnectionsInfo accepting_connections_info_ ABSL_GUARDED_BY(mutex_);
// A thread pool dedicated to running all the accept loops from
// StartAcceptingConnections().
MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
// A map of service_id -> ServerSocket. If map is non-empty, we
// are currently listening for incoming connections.
// WifiLanServerSocket instances are used from accept_loops_runner_,
// and thus require pointer stability.
absl::flat_hash_map<std::string, WifiLanServerSocket> server_sockets_
ABSL_GUARDED_BY(mutex_);
};
} // namespace connections
+185 -87
View File
@@ -20,6 +20,7 @@
#include "gtest/gtest.h"
#include "absl/strings/string_view.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.h"
@@ -42,9 +43,8 @@ constexpr FeatureFlags kTestCases[] = {
constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
constexpr absl::string_view kServiceInfoName{
"Simulated WifiLan service encrypted string #1"};
constexpr absl::string_view kEndpointName{"Simulated endpoint name"};
constexpr absl::string_view kServiceInfoName{"ServiceInfoName"};
constexpr absl::string_view kEndpointName{"EndpointName"};
constexpr absl::string_view kEndpointInfoKey{"n"};
class WifiLanTest : public ::testing::TestWithParam<FeatureFlags> {
@@ -56,54 +56,59 @@ class WifiLanTest : public ::testing::TestWithParam<FeatureFlags> {
MediumEnvironment& env_{MediumEnvironment::Instance()};
};
TEST_P(WifiLanTest, CanStartAcceptingConnectionsAndConnect) {
TEST_P(WifiLanTest, CanConnect) {
FeatureFlags feature_flags = GetParam();
env_.SetFeatureFlags(feature_flags);
env_.Start();
WifiLan wifi_lan_a;
WifiLan wifi_lan_b;
WifiLan wifi_lan_client;
WifiLan wifi_lan_server;
std::string service_id(kServiceID);
std::string service_info_name{kServiceInfoName};
std::string endpoint_info_name{kEndpointName};
CountDownLatch found_latch(1);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch accept_latch(1);
WifiLanSocket socket_for_server;
EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
service_id,
{
.accepted_cb =
[&socket_for_server, &accept_latch](WifiLanSocket 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_a.StartAdvertising(service_id, nsd_service_info);
wifi_lan_a.StartAcceptingConnections(
service_id,
{
.accepted_cb = [&accept_latch](
WifiLanSocket socket,
absl::string_view) { accept_latch.CountDown(); },
});
WifiLanService discovered_service;
wifi_lan_b.StartDiscovery(
wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
NsdServiceInfo discovered_service_info;
wifi_lan_client.StartDiscovery(
service_id,
{
.service_discovered_cb =
[&found_latch, &discovered_service](
WifiLanService& service, absl::string_view service_id) {
discovered_service = service;
NEARBY_LOG(INFO, "Discovered service=%p [impl=%p]", &service,
&service.GetImpl());
found_latch.CountDown();
[&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());
EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
ASSERT_TRUE(discovered_service.IsValid());
CancellationFlag flag;
WifiLanSocket socket =
wifi_lan_b.Connect(discovered_service, service_id, &flag);
WifiLanSocket socket_for_client =
wifi_lan_client.Connect(service_id, discovered_service_info, &flag);
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
EXPECT_TRUE(socket.IsValid());
wifi_lan_b.StopDiscovery(service_id);
wifi_lan_a.StopAcceptingConnections(service_id);
wifi_lan_a.StopAdvertising(service_id);
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();
}
@@ -111,56 +116,64 @@ TEST_P(WifiLanTest, CanCancelConnect) {
FeatureFlags feature_flags = GetParam();
env_.SetFeatureFlags(feature_flags);
env_.Start();
WifiLan wifi_lan_a;
WifiLan wifi_lan_b;
WifiLan wifi_lan_client;
WifiLan wifi_lan_server;
std::string service_id(kServiceID);
std::string service_info_name{kServiceInfoName};
std::string endpoint_info_name{kEndpointName};
CountDownLatch found_latch(1);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch accept_latch(1);
WifiLanSocket socket_for_server;
EXPECT_TRUE(wifi_lan_server.StartAcceptingConnections(
service_id,
{
.accepted_cb =
[&socket_for_server, &accept_latch](WifiLanSocket 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_a.StartAdvertising(service_id, nsd_service_info);
wifi_lan_a.StartAcceptingConnections(
service_id,
{
.accepted_cb = [&accept_latch](
WifiLanSocket socket,
absl::string_view) { accept_latch.CountDown(); },
});
WifiLanService discovered_service;
wifi_lan_b.StartDiscovery(
wifi_lan_server.StartAdvertising(service_id, nsd_service_info);
NsdServiceInfo discovered_service_info;
wifi_lan_client.StartDiscovery(
service_id,
{
.service_discovered_cb =
[&found_latch, &discovered_service](
WifiLanService& service, absl::string_view service_id) {
discovered_service = service;
NEARBY_LOG(INFO, "Discovered service=%p [impl=%p]", &service,
&service.GetImpl());
found_latch.CountDown();
[&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());
EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
ASSERT_TRUE(discovered_service.IsValid());
CancellationFlag flag(true);
WifiLanSocket socket =
wifi_lan_b.Connect(discovered_service, service_id, &flag);
WifiLanSocket 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(socket.IsValid());
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_FALSE(socket.IsValid());
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());
}
wifi_lan_b.StopDiscovery(service_id);
wifi_lan_a.StopAcceptingConnections(service_id);
wifi_lan_a.StopAdvertising(service_id);
env_.Stop();
}
@@ -181,42 +194,127 @@ TEST_F(WifiLanTest, CanConstructValidObject) {
TEST_F(WifiLanTest, CanStartAdvertising) {
env_.Start();
WifiLan wifi_lan_a;
WifiLan wifi_lan_b;
std::string service_id(kServiceID);
std::string service_info_name{kServiceInfoName};
std::string endpoint_info_name{kEndpointName};
CountDownLatch found_latch(1);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
wifi_lan_b.StartDiscovery(
service_id, DiscoveredServiceCallback{
.service_discovered_cb =
[&found_latch](WifiLanService& service,
absl::string_view service_id) {
found_latch.CountDown();
},
});
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),
endpoint_info_name);
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_id));
env_.Stop();
}
TEST_F(WifiLanTest, CanStartMultipleAdvertising) {
env_.Start();
WifiLan wifi_lan_a;
std::string service_id_1(kServiceID);
std::string service_id_2("com.google.location.nearby.apps.test_1");
std::string service_info_name_1(kServiceInfoName);
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),
endpoint_info_name);
NsdServiceInfo nsd_service_info_2;
nsd_service_info_2.SetServiceName(service_info_name_2);
nsd_service_info_2.SetTxtRecord(std::string(kEndpointInfoKey),
endpoint_info_name);
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_1, nsd_service_info_1));
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_2, nsd_service_info_2));
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_1));
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_2));
EXPECT_TRUE(wifi_lan_a.StopAcceptingConnections(service_id_1));
EXPECT_TRUE(wifi_lan_a.StopAcceptingConnections(service_id_2));
env_.Stop();
}
TEST_F(WifiLanTest, CanStartDiscovery) {
env_.Start();
WifiLan wifi_lan_a;
std::string service_id(kServiceID);
EXPECT_TRUE(
wifi_lan_a.StartDiscovery(service_id, DiscoveredServiceCallback{}));
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
env_.Stop();
}
TEST_F(WifiLanTest, CanStartMultipleDiscovery) {
env_.Start();
WifiLan wifi_lan_a;
std::string service_id_1(kServiceID);
std::string service_id_2("com.google.location.nearby.apps.test_1");
EXPECT_TRUE(
wifi_lan_a.StartDiscovery(service_id_1, DiscoveredServiceCallback{}));
EXPECT_TRUE(
wifi_lan_a.StartDiscovery(service_id_2, DiscoveredServiceCallback{}));
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_1));
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_2));
env_.Stop();
}
TEST_F(WifiLanTest, CanAdvertiseThatOtherMediumDiscover) {
env_.Start();
WifiLan wifi_lan_a;
WifiLan wifi_lan_b;
std::string service_id(kServiceID);
std::string service_info_name{kServiceInfoName};
std::string endpoint_info_name{kEndpointName};
CountDownLatch accept_latch(1);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch lost_latch(1);
wifi_lan_b.StartDiscovery(
service_id, DiscoveredServiceCallback{
.service_discovered_cb =
[&discovered_latch](NsdServiceInfo service_info,
const std::string& service_id) {
discovered_latch.CountDown();
},
.service_lost_cb =
[&lost_latch](NsdServiceInfo service_info,
const std::string& service_id) {
lost_latch.CountDown();
},
});
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),
endpoint_info_name);
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_id));
env_.Stop();
}
TEST_F(WifiLanTest, CanDiscoverThatOtherMediumAdvertise) {
env_.Start();
WifiLan wifi_lan_a;
WifiLan wifi_lan_b;
std::string service_id(kServiceID);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
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),
@@ -224,20 +322,20 @@ TEST_F(WifiLanTest, CanStartDiscovery) {
wifi_lan_b.StartAdvertising(service_id, nsd_service_info);
EXPECT_TRUE(wifi_lan_a.StartDiscovery(
service_id, {
service_id, DiscoveredServiceCallback{
.service_discovered_cb =
[&accept_latch](WifiLanService& service,
const std::string& service_id) {
accept_latch.CountDown();
[&discovered_latch](NsdServiceInfo service_info,
const std::string& service_id) {
discovered_latch.CountDown();
},
.service_lost_cb =
[&lost_latch](WifiLanService& service,
[&lost_latch](NsdServiceInfo service_info,
const std::string& service_id) {
lost_latch.CountDown();
},
}));
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
wifi_lan_b.StopAdvertising(service_id);
EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_b.StopAdvertising(service_id));
EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
env_.Stop();
@@ -1,344 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#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"
namespace location {
namespace nearby {
namespace connections {
namespace {
using FeatureFlags = FeatureFlags::Flags;
constexpr FeatureFlags kTestCases[] = {
FeatureFlags{
.enable_cancellation_flag = true,
},
FeatureFlags{
.enable_cancellation_flag = false,
},
};
constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
constexpr absl::string_view kServiceID{"com.google.location.nearby.apps.test"};
constexpr absl::string_view kServiceInfoName{"ServiceInfoName"};
constexpr absl::string_view kEndpointName{"EndpointName"};
constexpr absl::string_view kEndpointInfoKey{"n"};
class WifiLanV2Test : public ::testing::TestWithParam<FeatureFlags> {
protected:
using DiscoveredServiceCallback = WifiLanMediumV2::DiscoveredServiceCallback;
WifiLanV2Test() { env_.Stop(); }
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;
WifiLanV2 wifi_lan_b;
std::string service_id(kServiceID);
EXPECT_TRUE(wifi_lan_a.IsAvailable());
EXPECT_TRUE(wifi_lan_b.IsAvailable());
env_.Stop();
}
TEST_F(WifiLanV2Test, CanStartAdvertising) {
env_.Start();
WifiLanV2 wifi_lan_a;
std::string service_id(kServiceID);
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),
endpoint_info_name);
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
env_.Stop();
}
TEST_F(WifiLanV2Test, CanStartMultipleAdvertising) {
env_.Start();
WifiLanV2 wifi_lan_a;
std::string service_id_1(kServiceID);
std::string service_id_2("com.google.location.nearby.apps.test_1");
std::string service_info_name_1(kServiceInfoName);
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),
endpoint_info_name);
NsdServiceInfo nsd_service_info_2;
nsd_service_info_2.SetServiceName(service_info_name_2);
nsd_service_info_2.SetTxtRecord(std::string(kEndpointInfoKey),
endpoint_info_name);
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_1, nsd_service_info_1));
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id_2, nsd_service_info_2));
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_1));
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id_2));
env_.Stop();
}
TEST_F(WifiLanV2Test, CanStartDiscovery) {
env_.Start();
WifiLanV2 wifi_lan_a;
std::string service_id(kServiceID);
EXPECT_TRUE(
wifi_lan_a.StartDiscovery(service_id, DiscoveredServiceCallback{}));
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
env_.Stop();
}
TEST_F(WifiLanV2Test, CanStartMultipleDiscovery) {
env_.Start();
WifiLanV2 wifi_lan_a;
std::string service_id_1(kServiceID);
std::string service_id_2("com.google.location.nearby.apps.test_1");
EXPECT_TRUE(
wifi_lan_a.StartDiscovery(service_id_1, DiscoveredServiceCallback{}));
EXPECT_TRUE(
wifi_lan_a.StartDiscovery(service_id_2, DiscoveredServiceCallback{}));
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_1));
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id_2));
env_.Stop();
}
TEST_F(WifiLanV2Test, CanAdvertiseThatOtherMediumDiscover) {
env_.Start();
WifiLanV2 wifi_lan_a;
WifiLanV2 wifi_lan_b;
std::string service_id(kServiceID);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
CountDownLatch discovered_latch(1);
CountDownLatch lost_latch(1);
wifi_lan_b.StartDiscovery(
service_id, DiscoveredServiceCallback{
.service_discovered_cb =
[&discovered_latch](NsdServiceInfo service_info,
const std::string& service_id) {
discovered_latch.CountDown();
},
.service_lost_cb =
[&lost_latch](NsdServiceInfo service_info,
const std::string& service_id) {
lost_latch.CountDown();
},
});
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),
endpoint_info_name);
EXPECT_TRUE(wifi_lan_a.StartAdvertising(service_id, nsd_service_info));
EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_a.StopAdvertising(service_id));
EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_b.StopDiscovery(service_id));
env_.Stop();
}
TEST_F(WifiLanV2Test, CanDiscoverThatOtherMediumAdvertise) {
env_.Start();
WifiLanV2 wifi_lan_a;
WifiLanV2 wifi_lan_b;
std::string service_id(kServiceID);
std::string service_info_name(kServiceInfoName);
std::string endpoint_info_name(kEndpointName);
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),
endpoint_info_name);
wifi_lan_b.StartAdvertising(service_id, nsd_service_info);
EXPECT_TRUE(wifi_lan_a.StartDiscovery(
service_id, DiscoveredServiceCallback{
.service_discovered_cb =
[&discovered_latch](NsdServiceInfo service_info,
const std::string& service_id) {
discovered_latch.CountDown();
},
.service_lost_cb =
[&lost_latch](NsdServiceInfo service_info,
const std::string& service_id) {
lost_latch.CountDown();
},
}));
EXPECT_TRUE(discovered_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_b.StopAdvertising(service_id));
EXPECT_TRUE(lost_latch.Await(kWaitDuration).result());
EXPECT_TRUE(wifi_lan_a.StopDiscovery(service_id));
env_.Stop();
}
} // namespace
} // namespace connections
} // namespace nearby
} // namespace location
-409
View File
@@ -1,409 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "core/internal/mediums/wifi_lan_v2.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/strings/str_format.h"
#include "core/internal/mediums/utils.h"
#include "platform/public/logging.h"
#include "platform/public/mutex_lock.h"
namespace location {
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.
accept_loops_runner_.Shutdown();
}
bool WifiLanV2::IsAvailable() const {
MutexLock lock(&mutex_);
return IsAvailableLocked();
}
bool WifiLanV2::IsAvailableLocked() const { return medium_.IsValid(); }
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 "
"valid.";
return false;
}
if (IsAdvertisingLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "Failed to WifiLan advertise because we're already advertising.";
return false;
}
if (!IsAcceptingConnectionsLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "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="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_id=" << service_id;
return false;
}
NEARBY_LOGS(INFO) << "Turned on WifiLan advertising with nsd_service_info="
<< &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_id=" << service_id;
advertising_info_.Add(service_id, std::move(nsd_service_info));
return true;
}
bool WifiLanV2::StopAdvertising(const std::string& service_id) {
MutexLock lock(&mutex_);
if (!IsAdvertisingLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "Can't turn off WifiLan advertising; it is already off";
return false;
}
NEARBY_LOGS(INFO) << "Turned off WifiLan advertising with service_id="
<< service_id;
bool ret =
medium_.StopAdvertising(*advertising_info_.GetServiceInfo(service_id));
// Reset our bundle of advertising state to mark that we're no longer
// advertising for specific service_id.
advertising_info_.Remove(service_id);
return ret;
}
bool WifiLanV2::IsAdvertising(const std::string& service_id) {
MutexLock lock(&mutex_);
return IsAdvertisingLocked(service_id);
}
bool WifiLanV2::IsAdvertisingLocked(const std::string& service_id) {
return advertising_info_.Existed(service_id);
}
bool WifiLanV2::StartDiscovery(const std::string& service_id,
DiscoveredServiceCallback callback) {
MutexLock lock(&mutex_);
if (service_id.empty()) {
NEARBY_LOGS(INFO)
<< "Refusing to start WifiLan discovering with empty service_id.";
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOGS(INFO)
<< "Can't discover WifiLan services because WifiLan isn't available.";
return false;
}
if (IsDiscoveringLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "Refusing to start discovery of WifiLan services because another "
"discovery is already in-progress.";
return false;
}
std::string service_type = GenerateServiceType(service_id);
bool ret = medium_.StartDiscovery(service_id, service_type, callback);
if (!ret) {
NEARBY_LOGS(INFO) << "Failed to start discovery of WifiLan services.";
return false;
}
NEARBY_LOGS(INFO) << "Turned on WifiLan discovering with service_id="
<< service_id;
// Mark the fact that we're currently performing a WifiLan discovering.
discovering_info_.Add(service_id);
return true;
}
bool WifiLanV2::StopDiscovery(const std::string& service_id) {
MutexLock lock(&mutex_);
if (!IsDiscoveringLocked(service_id)) {
NEARBY_LOGS(INFO)
<< "Can't turn off WifiLan discovering because we never started "
"discovering.";
return false;
}
std::string service_type = GenerateServiceType(service_id);
NEARBY_LOGS(INFO) << "Turned off WifiLan discovering with service_id="
<< service_id << ", service_type=" << service_type;
bool ret = medium_.StopDiscovery(service_type);
discovering_info_.Remove(service_id);
return ret;
}
bool WifiLanV2::IsDiscovering(const std::string& service_id) {
MutexLock lock(&mutex_);
return IsDiscoveringLocked(service_id);
}
bool WifiLanV2::IsDiscoveringLocked(const std::string& service_id) {
return discovering_info_.Existed(service_id);
}
bool WifiLanV2::StartAcceptingConnections(const std::string& service_id,
AcceptedConnectionCallback callback) {
MutexLock lock(&mutex_);
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_);
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) {
MutexLock lock(&mutex_);
return IsAcceptingConnectionsLocked(service_id);
}
bool WifiLanV2::IsAcceptingConnectionsLocked(const std::string& service_id) {
return server_sockets_.find(service_id) != server_sockets_.end();
}
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;
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,
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) {
MutexLock lock(&mutex_);
// Socket to return. To allow for NRVO to work, it has to be a single object.
WifiLanSocketV2 socket;
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(ip_address, port, cancellation_flag);
if (!socket.IsValid()) {
NEARBY_LOGS(INFO) << "Failed to Connect via WifiLan [service_id="
<< service_id << "]";
}
return socket;
}
std::pair<std::string, int> WifiLanV2::GetCredentials(
const std::string& service_id) {
MutexLock lock(&mutex_);
const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) {
return std::pair<std::string, int>();
}
return std::pair<std::string, int>(it->second.GetIPAddress(),
it->second.GetPort());
}
std::string WifiLanV2::GenerateServiceType(const std::string& service_id) {
std::string service_id_hash_string;
const ByteArray service_id_hash = Utils::Sha256Hash(
service_id, NsdServiceInfo::kTypeFromServiceIdHashLength);
for (auto byte : std::string(service_id_hash)) {
absl::StrAppend(&service_id_hash_string, absl::StrFormat("%02X", byte));
}
return absl::StrFormat(NsdServiceInfo::kNsdTypeFormat,
service_id_hash_string);
}
} // namespace connections
} // namespace nearby
} // namespace location
-194
View File
@@ -1,194 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CORE_INTERNAL_MEDIUMS_WIFI_LAN_V2_H_
#define CORE_INTERNAL_MEDIUMS_WIFI_LAN_V2_H_
#include <cstdint>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "platform/base/byte_array.h"
#include "platform/base/cancellation_flag.h"
#include "platform/base/nsd_service_info.h"
#include "platform/public/multi_thread_executor.h"
#include "platform/public/mutex.h"
#include "platform/public/wifi_lan_v2.h"
namespace location {
namespace nearby {
namespace connections {
class WifiLanV2 {
public:
using DiscoveredServiceCallback = WifiLanMediumV2::DiscoveredServiceCallback;
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(WifiLanSocketV2 socket)> accepted_cb =
DefaultCallback<WifiLanSocketV2>();
};
WifiLanV2() = default;
~WifiLanV2();
// Returns true, if WifiLan communications are supported by a platform.
bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
// Sets custom service info name, endpoint info name in NsdServiceInfo and
// then enables WifiLan advertising.
// Returns true, if NsdServiceInfo is successfully set, and false otherwise.
bool StartAdvertising(const std::string& service_id,
NsdServiceInfo& nsd_service_info)
ABSL_LOCKS_EXCLUDED(mutex_);
// Disables WifiLan advertising.
// Returns false if no successful call StartAdvertising() was previously
// made, otherwise returns true.
bool StopAdvertising(const std::string& service_id)
ABSL_LOCKS_EXCLUDED(mutex_);
bool IsAdvertising(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
// Enables WifiLan discovery. Will report any discoverable services
// through a callback.
// Returns true, if discovery was enabled, false otherwise.
bool StartDiscovery(const std::string& service_id,
DiscoveredServiceCallback callback)
ABSL_LOCKS_EXCLUDED(mutex_);
// Disables WifiLan discovery.
bool StopDiscovery(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
bool IsDiscovering(const std::string& service_id) ABSL_LOCKS_EXCLUDED(mutex_);
// Starts a worker thread, creates a WifiLan socket, associates it with a
// service id.
bool StartAcceptingConnections(const std::string& service_id,
AcceptedConnectionCallback callback)
ABSL_LOCKS_EXCLUDED(mutex_);
// Closes socket corresponding to a service id.
bool StopAcceptingConnections(const std::string& service_id)
ABSL_LOCKS_EXCLUDED(mutex_);
bool IsAcceptingConnections(const std::string& service_id)
ABSL_LOCKS_EXCLUDED(mutex_);
// Establishes connection to WifiLan service that was might be started on
// another service with StartAcceptingConnections() using the same service_id.
// Blocks until connection is established, or server-side is terminated.
// Returns socket instance. On success, WifiLanSocket.IsValid() return true.
WifiLanSocketV2 Connect(const std::string& service_id,
const NsdServiceInfo& service_info,
CancellationFlag* cancellation_flag)
ABSL_LOCKS_EXCLUDED(mutex_);
// Establishes connection to WifiLan service by ip address and port for
// bandwidth upgradation.
// Returns socket instance. On success, WifiLanSocket.IsValid() return true.
WifiLanSocketV2 Connect(const std::string& service_id,
const std::string& ip_address, int port,
CancellationFlag* cancellation_flag)
ABSL_LOCKS_EXCLUDED(mutex_);
// Gets ip address + port for remote services on the network to identify and
// connect to this service.
//
// Credential is for the currently-hosted Wifi ServerSocket (if any).
std::pair<std::string, int> GetCredentials(const std::string& service_id)
ABSL_LOCKS_EXCLUDED(mutex_);
private:
struct AdvertisingInfo {
bool Empty() const { return nsd_service_infos.empty(); }
void Clear() { nsd_service_infos.clear(); }
void Add(const std::string& service_id,
const NsdServiceInfo& nsd_service_info) {
nsd_service_infos.insert({service_id, nsd_service_info});
}
void Remove(const std::string& service_id) {
nsd_service_infos.erase(service_id);
}
bool Existed(const std::string& service_id) const {
return nsd_service_infos.contains(service_id);
}
NsdServiceInfo* GetServiceInfo(const std::string& service_id) {
const auto& it = nsd_service_infos.find(service_id);
if (it == nsd_service_infos.end()) {
return nullptr;
}
return &it->second;
}
absl::flat_hash_map<std::string, NsdServiceInfo> nsd_service_infos;
};
struct DiscoveringInfo {
bool Empty() const { return service_ids.empty(); }
void Clear() { service_ids.clear(); }
void Add(const std::string& service_id) { service_ids.insert(service_id); }
void Remove(const std::string& service_id) {
service_ids.erase(service_id);
}
bool Existed(const std::string& service_id) const {
return service_ids.contains(service_id);
}
absl::flat_hash_set<std::string> service_ids;
};
static constexpr int kMaxConcurrentAcceptLoops = 5;
// Same as IsAvailable(), but must be called with mutex_ held.
bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Same as IsAdvertising(), but must be called with mutex_ held.
bool IsAdvertisingLocked(const std::string& service_id)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Same as IsDiscovering(), but must be called with mutex_ held.
bool IsDiscoveringLocked(const std::string& service_id)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Same as IsAcceptingConnections(), but must be called with mutex_ held.
bool IsAcceptingConnectionsLocked(const std::string& service_id)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Generates mDNS type.
std::string GenerateServiceType(const std::string& service_id);
mutable Mutex mutex_;
WifiLanMediumV2 medium_ ABSL_GUARDED_BY(mutex_);
AdvertisingInfo advertising_info_ ABSL_GUARDED_BY(mutex_);
DiscoveringInfo discovering_info_ ABSL_GUARDED_BY(mutex_);
// A thread pool dedicated to running all the accept loops from
// StartAcceptingConnections().
MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
// A map of service_id -> ServerSocket. If map is non-empty, we
// are currently listening for incoming connections.
// WifiLanServerSocket instances are used from accept_loops_runner_,
// and thus require pointer stability.
absl::flat_hash_map<std::string, WifiLanServerSocketV2> server_sockets_
ABSL_GUARDED_BY(mutex_);
};
} // namespace connections
} // namespace nearby
} // namespace location
#endif // CORE_INTERNAL_MEDIUMS_WIFI_LAN_H_