No changes to public files

PiperOrigin-RevId: 392585608
This commit is contained in:
hai007
2021-08-23 21:55:15 -07:00
committed by Copybara-Service
parent c73504e68d
commit 3e40931286
34 changed files with 2643 additions and 52 deletions
+6 -1
View File
@@ -55,6 +55,7 @@ cc_library(
compatible_with = ["//buildenv/target:non_prod"],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//third_party/nearby_connections/cpp/analytics:__subpackages__",
"//core:__subpackages__",
],
deps = [
@@ -72,8 +73,12 @@ cc_library(
hdrs = [
"event_logger.h",
],
compatible_with = ["//buildenv/target:non_prod"],
visibility = [
"//third_party/nearby_connections/cpp/analytics:__subpackages__",
],
deps = [
"//logs/proto/location/nearby:nearby_client_log_cc_proto",
"//third_party/nearby_connections/proto/analytics:connections_log_cc_proto",
],
)
+5
View File
@@ -15,10 +15,12 @@
#ifndef CORE_CORE_H_
#define CORE_CORE_H_
#include <functional>
#include <string>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "core/event_logger.h"
#include "core/internal/client_proxy.h"
#include "core/internal/service_controller.h"
#include "core/internal/service_controller_router.h"
@@ -34,6 +36,9 @@ namespace connections {
class Core {
public:
explicit Core(ServiceControllerRouter* router);
// Client needs to call this constructor if analytics logger is needed.
Core(analytics::EventLogger* event_logger, ServiceControllerRouter* router)
: client_(event_logger), router_(router) {}
~Core();
Core(Core&&);
Core& operator=(Core&&);
+2 -4
View File
@@ -15,11 +15,10 @@
#ifndef CORE_EVENT_LOGGER_H_
#define CORE_EVENT_LOGGER_H_
#include "logs/proto/location/nearby/nearby_client_log.proto.h"
#include "proto/analytics/connections_log.proto.h"
namespace location {
namespace nearby {
namespace connections {
namespace analytics {
// Allows callers to log |ConnectionsLog| collected at Nearby Connections
@@ -30,11 +29,10 @@ class EventLogger {
// Logs |ConnectionsLog| details. Might block to do I/O, e.g. upload
// synchronously to some metrics server.
virtual void Log(const logs::ConnectionsLog& connections_log) = 0;
virtual void Log(const proto::ConnectionsLog& connections_log) = 0;
};
} // namespace analytics
} // namespace connections
} // namespace nearby
} // namespace location
+2
View File
@@ -99,6 +99,7 @@ cc_library(
"//absl/strings",
"//absl/time",
"//absl/types:span",
"//third_party/nearby_connections/cpp/analytics",
"//core:core_types",
"//core/internal/mediums",
"//core/internal/mediums:utils",
@@ -194,6 +195,7 @@ cc_test(
"//absl/synchronization",
"//absl/time",
"//absl/types:span",
"//third_party/nearby_connections/cpp/analytics",
"//core:core_types",
"//core/internal/mediums",
"//core/internal/mediums:utils",
+24 -12
View File
@@ -25,9 +25,11 @@
#include "absl/container/flat_hash_set.h"
#include "absl/strings/escaping.h"
#include "absl/types/span.h"
#include "core/internal/mediums/utils.h"
#include "core/internal/offline_frames.h"
#include "core/internal/pcp_handler.h"
#include "core/options.h"
#include "platform/base/base64_utils.h"
#include "platform/base/bluetooth_utils.h"
#include "platform/public/logging.h"
#include "platform/public/system_clock.h"
@@ -342,6 +344,7 @@ void BasePcpHandler::OnEncryptionSuccessRunnable(
}
connection_info.SetCryptoContext(std::move(ukey2));
connection_info.connection_token = GetHashedConnectionToken(raw_auth_token);
NEARBY_LOGS(INFO)
<< "Register encrypted connection; wait for response; endpoint_id="
<< endpoint_id;
@@ -382,7 +385,8 @@ void BasePcpHandler::OnEncryptionSuccessRunnable(
.keep_alive_timeout_millis =
connection_info.options.keep_alive_timeout_millis,
},
std::move(connection_info.channel), connection_info.listener);
std::move(connection_info.channel), connection_info.listener,
connection_info.connection_token);
if (auto future_status = connection_info.result.lock()) {
NEARBY_LOGS(INFO) << "Connection established; Finalising future OK.";
@@ -629,9 +633,12 @@ BasePcpHandler::GetDiscoveredEndpoints(
return result;
}
void BasePcpHandler::PendingConnectionInfo::SetCryptoContext(
std::unique_ptr<UKey2Handshake> ukey2) {
this->ukey2 = std::move(ukey2);
mediums::PeerId BasePcpHandler::CreatePeerIdFromAdvertisement(
const std::string& service_id, const std::string& endpoint_id,
const ByteArray& endpoint_info) {
std::string seed =
absl::StrCat(service_id, endpoint_id, std::string(endpoint_info));
return mediums::PeerId::FromSeed(ByteArray(std::move(seed)));
}
bool BasePcpHandler::HasOutgoingConnections(ClientProxy* client) const {
@@ -1415,8 +1422,21 @@ ExceptionOr<OfflineFrame> BasePcpHandler::ReadConnectionRequestFrame(
return wrapped_frame;
}
std::string BasePcpHandler::GetHashedConnectionToken(
const ByteArray& token_bytes) {
auto token = std::string(token_bytes);
return location::nearby::Base64Utils::Encode(
Utils::Sha256Hash(token, token.size()))
.substr(0, kConnectionTokenLength);
}
///////////////////// BasePcpHandler::PendingConnectionInfo ///////////////////
void BasePcpHandler::PendingConnectionInfo::SetCryptoContext(
std::unique_ptr<UKey2Handshake> ukey2) {
this->ukey2 = std::move(ukey2);
}
BasePcpHandler::PendingConnectionInfo::~PendingConnectionInfo() {
auto future_status = result.lock();
if (future_status && !future_status->IsSet()) {
@@ -1443,14 +1463,6 @@ void BasePcpHandler::PendingConnectionInfo::LocalEndpointRejectedConnection(
client->LocalEndpointRejectedConnection(endpoint_id);
}
mediums::PeerId BasePcpHandler::CreatePeerIdFromAdvertisement(
const std::string& service_id, const std::string& endpoint_id,
const ByteArray& endpoint_info) {
std::string seed =
absl::StrCat(service_id, endpoint_id, std::string(endpoint_info));
return mediums::PeerId::FromSeed(ByteArray(std::move(seed)));
}
} // namespace connections
} // namespace nearby
} // namespace location
+8
View File
@@ -348,6 +348,9 @@ class BasePcpHandler : public PcpHandler,
// accepted. Crypto context is passed over to channel_manager_ before
// switching to connected state, where Payload may be exchanged.
std::unique_ptr<securegcm::UKey2Handshake> ukey2;
// Used in AnalyticsRecorder for devices connection tracking.
std::string connection_token;
};
// @EncryptionRunnerThread
@@ -382,6 +385,7 @@ class BasePcpHandler : public PcpHandler,
absl::Seconds(2);
static constexpr absl::Duration kRejectedConnectionCloseDelay =
absl::Seconds(2);
static constexpr int kConnectionTokenLength = 8;
void OnConnectionResponse(ClientProxy* client, const std::string& endpoint_id,
const OfflineFrame& frame);
@@ -446,6 +450,10 @@ class BasePcpHandler : public PcpHandler,
ExceptionOr<OfflineFrame> ReadConnectionRequestFrame(
EndpointChannel* channel);
// Returns an 8 characters length hashed string generated via a token byte
// array.
std::string GetHashedConnectionToken(const ByteArray& token_bytes);
void WaitForLatch(const std::string& method_name, CountDownLatch* latch);
Status WaitForResult(const std::string& method_name, std::int64_t client_id,
Future<Status>* future);
+38 -2
View File
@@ -15,7 +15,9 @@
#include "core/internal/client_proxy.h"
#include <cstdlib>
#include <functional>
#include <limits>
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
@@ -41,7 +43,12 @@ constexpr char kEndpointIdChars[] = {
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
ClientProxy::ClientProxy() : client_id_(Prng().NextInt64()) {}
ClientProxy::ClientProxy(analytics::EventLogger* event_logger)
: client_id_(Prng().NextInt64()) {
NEARBY_LOGS(INFO) << "ClientProxy ctor event_logger=" << event_logger;
analytics_recorder_ =
std::make_unique<analytics::AnalyticsRecorder>(event_logger);
}
ClientProxy::~ClientProxy() { Reset(); }
@@ -58,6 +65,14 @@ std::string ClientProxy::GetLocalEndpointId() {
return local_endpoint_id_;
}
std::string ClientProxy::GetConnectionToken(const std::string& endpoint_id) {
Connection* item = LookupConnection(endpoint_id);
if (item != nullptr) {
return item->connection_token;
}
return {};
}
std::string ClientProxy::GenerateLocalEndpointId() {
if (high_vis_mode_) {
if (!local_high_vis_mode_cache_endpoint_id_.empty()) {
@@ -82,6 +97,7 @@ void ClientProxy::Reset() {
StoppedDiscovery();
RemoveAllEndpoints();
ExitHighVisibilityMode();
analytics_recorder_->LogSession();
}
void ClientProxy::StartedAdvertising(
@@ -104,6 +120,10 @@ void ClientProxy::StartedAdvertising(
advertising_info_ = {service_id, listener};
advertising_options_ = advertising_options;
const std::vector<proto::connections::Medium> medium_vector(mediums.begin(),
mediums.end());
analytics_recorder_->OnStartAdvertising(strategy, medium_vector);
}
void ClientProxy::StoppedAdvertising() {
@@ -113,6 +133,7 @@ void ClientProxy::StoppedAdvertising() {
if (IsAdvertising()) {
advertising_info_.Clear();
analytics_recorder_->OnStopAdvertising();
}
// advertising_options_ is purposefully not cleared here.
ResetLocalEndpointIdIfNeeded();
@@ -146,6 +167,10 @@ void ClientProxy::StartedDiscovery(
MutexLock lock(&mutex_);
discovery_info_ = DiscoveryInfo{service_id, listener};
discovery_options_ = discovery_options;
const std::vector<proto::connections::Medium> medium_vector(mediums.begin(),
mediums.end());
analytics_recorder_->OnStartDiscovery(strategy, medium_vector);
}
void ClientProxy::StoppedDiscovery() {
@@ -154,6 +179,7 @@ void ClientProxy::StoppedDiscovery() {
if (IsDiscovering()) {
discovered_endpoint_ids_.clear();
discovery_info_.Clear();
analytics_recorder_->OnStopDiscovery();
}
// discovery_options_ is purposefully not cleared here.
ResetLocalEndpointIdIfNeeded();
@@ -203,6 +229,7 @@ void ClientProxy::OnEndpointFound(const std::string& service_id,
discovered_endpoint_ids_.insert(endpoint_id);
discovery_info_.listener.endpoint_found_cb(endpoint_id, endpoint_info,
service_id);
analytics_recorder_->OnEndpointFound(medium);
}
void ClientProxy::OnEndpointLost(const std::string& service_id,
@@ -234,7 +261,8 @@ void ClientProxy::OnEndpointLost(const std::string& service_id,
void ClientProxy::OnConnectionInitiated(const std::string& endpoint_id,
const ConnectionResponseInfo& info,
const ConnectionOptions& options,
const ConnectionListener& listener) {
const ConnectionListener& listener,
const std::string& connection_token) {
MutexLock lock(&mutex_);
// Whether this is incoming or outgoing, the local and remote endpoints both
@@ -245,6 +273,7 @@ void ClientProxy::OnConnectionInitiated(const std::string& endpoint_id,
.is_incoming = info.is_incoming_connection,
.connection_listener = listener,
.connection_options = options,
.connection_token = connection_token,
});
// Instead of using structured binding which is nice, but banned
// (can not use c++17 features, until chromium does) we unpack manually.
@@ -265,6 +294,9 @@ void ClientProxy::OnConnectionInitiated(const std::string& endpoint_id,
if (info.is_incoming_connection) {
// Add CancellationFlag for advertisers once encryption succeeds.
AddCancellationFlag(endpoint_id);
analytics_recorder_->OnConnectionRequestReceived(endpoint_id);
} else {
analytics_recorder_->OnConnectionRequestSent(endpoint_id);
}
}
@@ -449,6 +481,7 @@ void ClientProxy::LocalEndpointAcceptedConnection(
if (item != nullptr) {
item->payload_listener = listener;
}
analytics_recorder_->OnLocalEndpointAccepted(endpoint_id);
}
void ClientProxy::LocalEndpointRejectedConnection(
@@ -463,6 +496,7 @@ void ClientProxy::LocalEndpointRejectedConnection(
}
AppendConnectionStatus(endpoint_id, Connection::kLocalEndpointRejected);
analytics_recorder_->OnLocalEndpointRejected(endpoint_id);
}
void ClientProxy::RemoteEndpointAcceptedConnection(
@@ -477,6 +511,7 @@ void ClientProxy::RemoteEndpointAcceptedConnection(
}
AppendConnectionStatus(endpoint_id, Connection::kRemoteEndpointAccepted);
analytics_recorder_->OnRemoteEndpointAccepted(endpoint_id);
}
void ClientProxy::RemoteEndpointRejectedConnection(
@@ -491,6 +526,7 @@ void ClientProxy::RemoteEndpointRejectedConnection(
}
AppendConnectionStatus(endpoint_id, Connection::kRemoteEndpointRejected);
analytics_recorder_->OnRemoteEndpointRejected(endpoint_id);
}
bool ClientProxy::IsConnectionAccepted(const std::string& endpoint_id) const {
+12 -2
View File
@@ -16,9 +16,11 @@
#define CORE_INTERNAL_CLIENT_PROXY_H_
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
#include "third_party/nearby_connections/cpp/analytics/analytics_recorder.h"
#include "core/listeners.h"
#include "core/options.h"
#include "core/status.h"
@@ -46,7 +48,7 @@ class ClientProxy final {
static constexpr absl::Duration
kHighPowerAdvertisementEndpointIdCacheTimeout = absl::Seconds(30);
ClientProxy();
explicit ClientProxy(analytics::EventLogger* event_logger = nullptr);
~ClientProxy();
ClientProxy(ClientProxy&&) = default;
ClientProxy& operator=(ClientProxy&&) = default;
@@ -55,6 +57,8 @@ class ClientProxy final {
std::string GetLocalEndpointId();
std::string GetConnectionToken(const std::string& endpoint_id);
// Clears all the runtime state of this client.
void Reset();
@@ -98,7 +102,8 @@ class ClientProxy final {
void OnConnectionInitiated(const std::string& endpoint_id,
const ConnectionResponseInfo& info,
const ConnectionOptions& options,
const ConnectionListener& listener);
const ConnectionListener& listener,
const std::string& connection_token);
// Proxies to the client's ConnectionListener::OnAccepted() callback.
void OnConnectionAccepted(const std::string& endpoint_id);
@@ -205,6 +210,7 @@ class ClientProxy final {
ConnectionListener connection_listener;
PayloadListener payload_listener;
ConnectionOptions connection_options;
std::string connection_token;
};
struct AdvertisingInfo {
@@ -298,6 +304,10 @@ class ClientProxy final {
// A default cancellation flag with isCancelled set be true.
std::unique_ptr<CancellationFlag> default_cancellation_flag_ =
std::make_unique<CancellationFlag>(true);
// An analytics logger with |EventLogger| provided by client, which is default
// nullptr as no-op.
std::unique_ptr<analytics::AnalyticsRecorder> analytics_recorder_;
};
} // namespace connections
+4 -3
View File
@@ -131,10 +131,11 @@ class ClientProxyTest : public ::testing::TestWithParam<FeatureFlags> {
EXPECT_CALL(mock_discovery_connection_.initiated_cb, Call).Times(1);
const std::string auth_token{"auth_token"};
const ByteArray raw_auth_token{auth_token};
const std::string connection_token{"conntokn"};
advertising_connection_info_.remote_endpoint_info = endpoint.info;
client->OnConnectionInitiated(endpoint.id, advertising_connection_info_,
connection_options_,
discovery_connection_listener_);
client->OnConnectionInitiated(
endpoint.id, advertising_connection_info_, connection_options_,
discovery_connection_listener_, connection_token);
EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint.id));
}
+5 -2
View File
@@ -353,7 +353,8 @@ void EndpointManager::RegisterEndpoint(ClientProxy* client,
const ConnectionResponseInfo& info,
const ConnectionOptions& options,
std::unique_ptr<EndpointChannel> channel,
const ConnectionListener& listener) {
const ConnectionListener& listener,
const std::string& connection_token) {
CountDownLatch latch(1);
// NOTE (unique_ptr<> capture):
@@ -366,6 +367,7 @@ void EndpointManager::RegisterEndpoint(ClientProxy* client,
channel = channel.release(),
&endpoint_id, &info,
&options, &listener,
&connection_token,
&latch]() {
if (endpoints_.contains(endpoint_id)) {
NEARBY_LOGS(WARNING) << "Registering duplicate endpoint " << endpoint_id;
@@ -440,7 +442,8 @@ void EndpointManager::RegisterEndpoint(ClientProxy* client,
// It's now time to let the client know of this new connection so that
// they can accept or reject it.
client->OnConnectionInitiated(endpoint_id, info, options, listener);
client->OnConnectionInitiated(endpoint_id, info, options, listener,
connection_token);
latch.CountDown();
});
latch.Await();
+2 -1
View File
@@ -103,7 +103,8 @@ class EndpointManager {
const ConnectionResponseInfo& info,
const ConnectionOptions& options,
std::unique_ptr<EndpointChannel> channel,
const ConnectionListener& listener);
const ConnectionListener& listener,
const std::string& connection_token);
// Called when a client explicitly asks to disconnect from this endpoint. In
// this case, we do not notify the client of onDisconnected().
void UnregisterEndpoint(ClientProxy* client, const std::string& endpoint_id);
+2 -1
View File
@@ -108,7 +108,7 @@ class EndpointManagerTest : public ::testing::Test {
.WillRepeatedly(Return(start_time_));
EXPECT_CALL(mock_listener_.initiated_cb, Call).Times(1);
em_.RegisterEndpoint(&client_, endpoint_id_, info_, options_,
std::move(channel), listener_);
std::move(channel), listener_, connection_token);
if (should_close) {
EXPECT_TRUE(done.Await(absl::Milliseconds(1000)).result());
}
@@ -151,6 +151,7 @@ class EndpointManagerTest : public ::testing::Test {
.bandwidth_changed_cb =
mock_listener_.bandwidth_changed_cb.AsStdFunction(),
};
std::string connection_token = "conntokn";
absl::Time start_time_{absl::Now()};
};
@@ -148,8 +148,9 @@ class ServiceControllerRouterTest : public testing::Test {
.raw_authentication_token = ByteArray{"auth_token"},
.is_incoming_connection = true,
};
std::string connection_token{"conntokn"};
client->OnConnectionInitiated(endpoint_id, response_info, options,
request_info.listener);
request_info.listener, connection_token);
EXPECT_TRUE(client->HasPendingConnectionToEndpoint(endpoint_id));
}