Format all the files in CL786733783

PiperOrigin-RevId: 786873870
This commit is contained in:
hai007
2025-07-24 16:25:18 -07:00
committed by Copybara-Service
parent b3d9a930ca
commit 00a2999269
87 changed files with 1406 additions and 1719 deletions
-1
View File
@@ -121,7 +121,6 @@ cc_test(
"//internal/platform/implementation/g3", # build_cleaner: keep "//internal/platform/implementation/g3", # build_cleaner: keep
"@com_github_protobuf_matchers//protobuf-matchers", "@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings", "@com_google_absl//absl/strings",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main", "@com_google_googletest//:gtest_main",
], ],
) )
+1 -2
View File
@@ -283,8 +283,7 @@ void NcCloseService(NC_INSTANCE instance) {
} }
nc_context->core->StopAllEndpoints([](::nearby::connections::Status status) { nc_context->core->StopAllEndpoints([](::nearby::connections::Status status) {
LOG(INFO) << "Stopping all endpoints with status " LOG(INFO) << "Stopping all endpoints with status " << status.ToString();
<< status.ToString();
}); });
kNcContextMap->erase(nc_context->core); kNcContextMap->erase(nc_context->core);
-1
View File
@@ -167,7 +167,6 @@ TEST(CoreTest, DisconnectFailsWithEmptyEndpoint) {
EXPECT_EQ(final_status.value, Status::kEndpointUnknown); EXPECT_EQ(final_status.value, Status::kEndpointUnknown);
} }
TEST(CoreTest, SendPayloadCallsScRouter) { TEST(CoreTest, SendPayloadCallsScRouter) {
MockServiceControllerRouter mock_controller; MockServiceControllerRouter mock_controller;
// Called when Core is destroyed. // Called when Core is destroyed.
+19 -26
View File
@@ -93,8 +93,7 @@ void ListenerInitiatedCB(
NC_INSTANCE instance, int endpoint_id, NC_INSTANCE instance, int endpoint_id,
const NC_CONNECTION_RESPONSE_INFO *connection_response_info, const NC_CONNECTION_RESPONSE_INFO *connection_response_info,
void *context) { void *context) {
LOG(INFO) << "Advertising initiated: id=" LOG(INFO) << "Advertising initiated: id=" << GetEndpointIdString(endpoint_id);
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_endpoint_id = { Dart_CObject dart_object_endpoint_id = {
.type = Dart_CObject_Type::Dart_CObject_kInt32, .type = Dart_CObject_Type::Dart_CObject_kInt32,
@@ -127,8 +126,7 @@ void ListenerInitiatedCB(
} }
void ListenerAcceptedCB(NC_INSTANCE instance, int endpoint_id, void *context) { void ListenerAcceptedCB(NC_INSTANCE instance, int endpoint_id, void *context) {
LOG(INFO) << "Advertising accepted: id=" LOG(INFO) << "Advertising accepted: id=" << GetEndpointIdString(endpoint_id);
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_accepted; Dart_CObject dart_object_accepted;
dart_object_accepted.type = Dart_CObject_kInt32; dart_object_accepted.type = Dart_CObject_kInt32;
dart_object_accepted.value.as_int32 = endpoint_id; dart_object_accepted.value.as_int32 = endpoint_id;
@@ -142,8 +140,7 @@ void ListenerAcceptedCB(NC_INSTANCE instance, int endpoint_id, void *context) {
void ListenerRejectedCB(NC_INSTANCE instance, int endpoint_id, NC_STATUS status, void ListenerRejectedCB(NC_INSTANCE instance, int endpoint_id, NC_STATUS status,
void *context) { void *context) {
LOG(INFO) << "Advertising rejected: id=" LOG(INFO) << "Advertising rejected: id=" << GetEndpointIdString(endpoint_id);
<< GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_rejected; Dart_CObject dart_object_rejected;
dart_object_rejected.type = Dart_CObject_kInt32; dart_object_rejected.type = Dart_CObject_kInt32;
dart_object_rejected.value.as_int32 = endpoint_id; dart_object_rejected.value.as_int32 = endpoint_id;
@@ -158,7 +155,7 @@ void ListenerRejectedCB(NC_INSTANCE instance, int endpoint_id, NC_STATUS status,
void ListenerDisconnectedCB(NC_INSTANCE instance, int endpoint_id, void ListenerDisconnectedCB(NC_INSTANCE instance, int endpoint_id,
void *context) { void *context) {
LOG(INFO) << "Advertising disconnected: id=" LOG(INFO) << "Advertising disconnected: id="
<< GetEndpointIdString(endpoint_id); << GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_disconnected; Dart_CObject dart_object_disconnected;
dart_object_disconnected.type = Dart_CObject_kInt32; dart_object_disconnected.type = Dart_CObject_kInt32;
dart_object_disconnected.value.as_int32 = endpoint_id; dart_object_disconnected.value.as_int32 = endpoint_id;
@@ -173,7 +170,7 @@ void ListenerDisconnectedCB(NC_INSTANCE instance, int endpoint_id,
void ListenerBandwidthChangedCB(NC_INSTANCE instance, int endpoint_id, void ListenerBandwidthChangedCB(NC_INSTANCE instance, int endpoint_id,
NC_MEDIUM medium, void *context) { NC_MEDIUM medium, void *context) {
LOG(INFO) << "Advertising bandwidth changed: id=" LOG(INFO) << "Advertising bandwidth changed: id="
<< GetEndpointIdString(endpoint_id); << GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_bandwidth_changed; Dart_CObject dart_object_bandwidth_changed;
dart_object_bandwidth_changed.type = Dart_CObject_kInt32; dart_object_bandwidth_changed.type = Dart_CObject_kInt32;
@@ -189,10 +186,9 @@ void ListenerBandwidthChangedCB(NC_INSTANCE instance, int endpoint_id,
void ListenerEndpointFoundCB(NC_INSTANCE instance, int endpoint_id, void ListenerEndpointFoundCB(NC_INSTANCE instance, int endpoint_id,
const NC_DATA *endpoint_info, const NC_DATA *endpoint_info,
const NC_DATA *service_id, void *context) { const NC_DATA *service_id, void *context) {
LOG(INFO) << "Device discovered: id=" LOG(INFO) << "Device discovered: id=" << GetEndpointIdString(endpoint_id);
<< GetEndpointIdString(endpoint_id);
LOG(INFO) << "Device discovered: service_id=" LOG(INFO) << "Device discovered: service_id="
<< std::string(service_id->data, service_id->size); << std::string(service_id->data, service_id->size);
std::string endpoint_info_str = absl::BytesToHexString( std::string endpoint_info_str = absl::BytesToHexString(
absl::string_view(endpoint_info->data, endpoint_info->size)); absl::string_view(endpoint_info->data, endpoint_info->size));
@@ -244,7 +240,7 @@ void ListenerEndpointDistanceChangedCB(NC_INSTANCE instance, int endpoint_id,
void *context) { void *context) {
(void)distance_info; // Avoid unused parameter warning (void)distance_info; // Avoid unused parameter warning
LOG(INFO) << "Device distance changed: id=" LOG(INFO) << "Device distance changed: id="
<< GetEndpointIdString(endpoint_id); << GetEndpointIdString(endpoint_id);
Dart_CObject dart_object_distance_changed; Dart_CObject dart_object_distance_changed;
dart_object_distance_changed.type = Dart_CObject_kInt32; dart_object_distance_changed.type = Dart_CObject_kInt32;
dart_object_distance_changed.value.as_int32 = endpoint_id; dart_object_distance_changed.value.as_int32 = endpoint_id;
@@ -259,9 +255,8 @@ void ListenerEndpointDistanceChangedCB(NC_INSTANCE instance, int endpoint_id,
void ListenerPayloadCB(NC_INSTANCE instance, int endpoint_id, void ListenerPayloadCB(NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD *payload, void *context) { const NC_PAYLOAD *payload, void *context) {
LOG(INFO) << "Payload callback called. id: " LOG(INFO) << "Payload callback called. id: "
<< GetEndpointIdString(endpoint_id) << GetEndpointIdString(endpoint_id)
<< ", payload_id: " << payload->id << ", payload_id: " << payload->id << ", type: " << payload->type;
<< ", type: " << payload->type;
Dart_CObject dart_object_endpoint_id; Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kInt32; dart_object_endpoint_id.type = Dart_CObject_kInt32;
@@ -361,12 +356,12 @@ void ListenerPayloadProgressCB(
NC_INSTANCE instance, int endpoint_id, NC_INSTANCE instance, int endpoint_id,
const NC_PAYLOAD_PROGRESS_INFO *payload_progress_info, void *context) { const NC_PAYLOAD_PROGRESS_INFO *payload_progress_info, void *context) {
LOG(INFO) << "Payload progress callback called. id: " LOG(INFO) << "Payload progress callback called. id: "
<< GetEndpointIdString(endpoint_id) << GetEndpointIdString(endpoint_id)
<< ", payload_id: " << payload_progress_info->id << ", payload_id: " << payload_progress_info->id
<< ", bytes transferred: " << ", bytes transferred: "
<< payload_progress_info->bytes_transferred << payload_progress_info->bytes_transferred
<< ", total: " << payload_progress_info->total_bytes << ", total: " << payload_progress_info->total_bytes
<< ", status: " << payload_progress_info->status; << ", status: " << payload_progress_info->status;
Dart_CObject dart_object_endpoint_id; Dart_CObject dart_object_endpoint_id;
dart_object_endpoint_id.type = Dart_CObject_kInt32; dart_object_endpoint_id.type = Dart_CObject_kInt32;
dart_object_endpoint_id.value.as_int32 = endpoint_id; dart_object_endpoint_id.value.as_int32 = endpoint_id;
@@ -449,8 +444,7 @@ void EnableBleV2Dart(NC_INSTANCE instance, int64_t enable,
status); status);
}, },
nullptr); nullptr);
LOG(INFO) << "EnableBleV2Dart callback is called with enable=" LOG(INFO) << "EnableBleV2Dart callback is called with enable=" << enable;
<< enable;
} }
void StartAdvertisingDart(NC_INSTANCE instance, DataDart service_id, void StartAdvertisingDart(NC_INSTANCE instance, DataDart service_id,
@@ -784,9 +778,8 @@ void SendPayloadDart(NC_INSTANCE instance, int endpoint_id,
} }
case PAYLOAD_TYPE_FILE: case PAYLOAD_TYPE_FILE:
LOG(INFO) << "File name: " LOG(INFO) << "File name: "
<< std::string(payload_dart.data.data, << std::string(payload_dart.data.data, payload_dart.data.size)
payload_dart.data.size) << ", size " << payload_dart.size;
<< ", size " << payload_dart.size;
std::string file_name_str(payload_dart.data.data, payload_dart.data.size); std::string file_name_str(payload_dart.data.data, payload_dart.data.size);
NC_PAYLOAD payload{}; NC_PAYLOAD payload{};
@@ -45,7 +45,7 @@ namespace analytics {
namespace { namespace {
// const char kVersion_1_0_0[] = "v1.0.0"; // const char kVersion_1_0_0[] = "v1.0.0";
const char kVersion [] = "v1.5.0"; const char kVersion[] = "v1.5.0";
constexpr absl::string_view kOnStartClientSession = "OnStartClientSession"; constexpr absl::string_view kOnStartClientSession = "OnStartClientSession";
const absl::Duration kConnectionTokenMaxLife = absl::Hours(24); const absl::Duration kConnectionTokenMaxLife = absl::Hours(24);
@@ -164,8 +164,7 @@ OperationResultCategory ConvertToOperationResultCategory(
AnalyticsRecorder::AnalyticsRecorder(EventLogger *event_logger) AnalyticsRecorder::AnalyticsRecorder(EventLogger *event_logger)
: event_logger_(event_logger) { : event_logger_(event_logger) {
LOG(INFO) << "Start AnalyticsRecorder ctor event_logger_=" LOG(INFO) << "Start AnalyticsRecorder ctor event_logger_=" << event_logger_;
<< event_logger_;
LogStartSession(); LogStartSession();
} }
@@ -173,13 +172,11 @@ AnalyticsRecorder::AnalyticsRecorder(EventLogger *event_logger,
bool no_record_time_millis) bool no_record_time_millis)
: event_logger_(event_logger), : event_logger_(event_logger),
no_record_time_millis_(no_record_time_millis) { no_record_time_millis_(no_record_time_millis) {
LOG(INFO) << "Start AnalyticsRecorder ctor event_logger_=" LOG(INFO) << "Start AnalyticsRecorder ctor event_logger_=" << event_logger_;
<< event_logger_;
LogStartSession(); LogStartSession();
} }
AnalyticsRecorder::~AnalyticsRecorder() { AnalyticsRecorder::~AnalyticsRecorder() = default;
}
bool AnalyticsRecorder::IsSessionLogged() { bool AnalyticsRecorder::IsSessionLogged() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
@@ -206,7 +203,7 @@ void AnalyticsRecorder::OnStartAdvertising(
} }
if (!strategy.IsValid()) { if (!strategy.IsValid()) {
LOG(INFO) << "AnalyticsRecorder OnStartAdvertising with unknown " LOG(INFO) << "AnalyticsRecorder OnStartAdvertising with unknown "
"strategy, bail out."; "strategy, bail out.";
return; return;
} }
// Initialize/update a StrategySession. // Initialize/update a StrategySession.
@@ -268,7 +265,7 @@ void AnalyticsRecorder::OnStartDiscovery(
} }
if (!strategy.IsValid()) { if (!strategy.IsValid()) {
LOG(INFO) << "AnalyticsRecorder OnStartDiscovery unknown " LOG(INFO) << "AnalyticsRecorder OnStartDiscovery unknown "
"strategy enter, bail out."; "strategy enter, bail out.";
return; return;
} }
@@ -347,7 +344,7 @@ void AnalyticsRecorder::OnEndpointFound(Medium medium) {
} }
if (current_discovery_phase_ == nullptr) { if (current_discovery_phase_ == nullptr) {
LOG(INFO) << "Unable to record discovered endpoint due to null " LOG(INFO) << "Unable to record discovered endpoint due to null "
"current_discovery_phase_"; "current_discovery_phase_";
return; return;
} }
ConnectionsLog::DiscoveredEndpoint *discovered_endpoint = ConnectionsLog::DiscoveredEndpoint *discovered_endpoint =
@@ -454,7 +451,7 @@ void AnalyticsRecorder::OnIncomingConnectionAttempt(
} }
if (current_strategy_session_ == nullptr) { if (current_strategy_session_ == nullptr) {
LOG(INFO) << "Unable to record incoming connection attempt due to " LOG(INFO) << "Unable to record incoming connection attempt due to "
"null current_strategy_session_"; "null current_strategy_session_";
return; return;
} }
@@ -533,7 +530,7 @@ void AnalyticsRecorder::OnOutgoingConnectionAttempt(
} }
if (current_strategy_session_ == nullptr) { if (current_strategy_session_ == nullptr) {
LOG(INFO) << "Unable to record outgoing connection attempt due to " LOG(INFO) << "Unable to record outgoing connection attempt due to "
"null current_strategy_session_"; "null current_strategy_session_";
return; return;
} }
@@ -649,10 +646,10 @@ void AnalyticsRecorder::OnConnectionClosed(const std::string &endpoint_id,
SafeDisconnectionResult result) { SafeDisconnectionResult result) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << __func__ LOG(INFO) << __func__
<< ": OnConnectionClosed is called with endpoint_id:" << ": OnConnectionClosed is called with endpoint_id:" << endpoint_id
<< endpoint_id << ", medium:" << Medium_Name(medium) << ", medium:" << Medium_Name(medium)
<< ", reason:" << DisconnectionReason_Name(reason) << ", reason:" << DisconnectionReason_Name(reason)
<< ", result:" << result; << ", result:" << result;
if (!CanRecordAnalyticsLocked("OnConnectionClosed")) { if (!CanRecordAnalyticsLocked("OnConnectionClosed")) {
return; return;
@@ -660,8 +657,7 @@ void AnalyticsRecorder::OnConnectionClosed(const std::string &endpoint_id,
if (current_strategy_session_ == nullptr) { if (current_strategy_session_ == nullptr) {
VLOG(1) << "AnalyticsRecorder CanRecordAnalytics Unexpected call " VLOG(1) << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
<< __func__ << __func__ << " since current_strategy_session_ is required.";
<< " since current_strategy_session_ is required.";
return; return;
} }
@@ -887,7 +883,7 @@ void AnalyticsRecorder::OnErrorCode(const ErrorCodeParams &params) {
connections_log.set_allocated_error_code(error_code.release()); connections_log.set_allocated_error_code(error_code.release());
VLOG(1) << "AnalyticsRecorder LogErrorCode connections_log=" VLOG(1) << "AnalyticsRecorder LogErrorCode connections_log="
<< connections_log.DebugString(); // NOLINT << connections_log.DebugString(); // NOLINT
event_logger_->Log(connections_log); event_logger_->Log(connections_log);
} }
@@ -895,10 +891,9 @@ void AnalyticsRecorder::OnErrorCode(const ErrorCodeParams &params) {
void AnalyticsRecorder::LogStartSession() { void AnalyticsRecorder::LogStartSession() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (start_client_session_was_logged_) { if (start_client_session_was_logged_) {
LOG(WARNING) LOG(WARNING) << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
<< "AnalyticsRecorder CanRecordAnalytics Unexpected call " << kOnStartClientSession
<< kOnStartClientSession << " after start client session has already been logged.";
<< " after start client session has already been logged.";
return; return;
} }
@@ -1011,15 +1006,14 @@ OperationResultCode AnalyticsRecorder::GetChannelIoErrorResultCodeFromMedium(
bool AnalyticsRecorder::CanRecordAnalyticsLocked( bool AnalyticsRecorder::CanRecordAnalyticsLocked(
absl::string_view method_name) { absl::string_view method_name) {
VLOG(1) << "AnalyticsRecorder LogEvent " << method_name VLOG(1) << "AnalyticsRecorder LogEvent " << method_name << " is calling.";
<< " is calling.";
if (event_logger_ == nullptr) { if (event_logger_ == nullptr) {
return false; return false;
} }
if (session_was_logged_) { if (session_was_logged_) {
VLOG(1) << "AnalyticsRecorder CanRecordAnalytics Unexpected call " VLOG(1) << "AnalyticsRecorder CanRecordAnalytics Unexpected call "
<< method_name << " after session has already been logged."; << method_name << " after session has already been logged.";
return false; return false;
} }
@@ -1036,7 +1030,7 @@ void AnalyticsRecorder::LogClientSessionLocked() {
connections_log.set_version(kVersion); connections_log.set_version(kVersion);
VLOG(1) << "AnalyticsRecorder LogClientSession connections_log=" VLOG(1) << "AnalyticsRecorder LogClientSession connections_log="
<< connections_log.DebugString(); // NOLINT << connections_log.DebugString(); // NOLINT
event_logger_->Log(connections_log); event_logger_->Log(connections_log);
client_session_ = nullptr; client_session_ = nullptr;
@@ -1048,7 +1042,7 @@ void AnalyticsRecorder::LogEvent(EventType event_type) {
connections_log.set_version(kVersion); connections_log.set_version(kVersion);
VLOG(1) << "AnalyticsRecorder LogEvent connections_log=" VLOG(1) << "AnalyticsRecorder LogEvent connections_log="
<< connections_log.DebugString(); // NOLINT << connections_log.DebugString(); // NOLINT
event_logger_->Log(connections_log); event_logger_->Log(connections_log);
} }
@@ -1092,7 +1086,7 @@ void AnalyticsRecorder::RecordAdvertisingPhaseDurationAndReasonLocked(
bool on_stop) const { bool on_stop) const {
if (current_advertising_phase_ == nullptr) { if (current_advertising_phase_ == nullptr) {
LOG(INFO) << "Unable to record advertising phase duration due to " LOG(INFO) << "Unable to record advertising phase duration due to "
"null current_advertising_phase_"; "null current_advertising_phase_";
return; return;
} }
if (!current_advertising_phase_->has_duration_millis() && if (!current_advertising_phase_->has_duration_millis() &&
@@ -1123,7 +1117,7 @@ void AnalyticsRecorder::FinishAdvertisingPhaseLocked() {
*std::move(current_advertising_phase_); *std::move(current_advertising_phase_);
} else { } else {
LOG(INFO) << "Unable to record advertising phase due to null " LOG(INFO) << "Unable to record advertising phase due to null "
"current_strategy_session_"; "current_strategy_session_";
} }
} }
incoming_connection_requests_.clear(); incoming_connection_requests_.clear();
@@ -1133,7 +1127,7 @@ void AnalyticsRecorder::RecordDiscoveryPhaseDurationAndReasonLocked(
bool on_stop) const { bool on_stop) const {
if (current_discovery_phase_ == nullptr) { if (current_discovery_phase_ == nullptr) {
LOG(INFO) << "Unable to record discovery phase duration due to " LOG(INFO) << "Unable to record discovery phase duration due to "
"null current_discovery_phase_"; "null current_discovery_phase_";
return; return;
} }
if (!current_discovery_phase_->has_duration_millis() && if (!current_discovery_phase_->has_duration_millis() &&
@@ -1165,7 +1159,7 @@ void AnalyticsRecorder::FinishDiscoveryPhaseLocked() {
*std::move(current_discovery_phase_); *std::move(current_discovery_phase_);
} else { } else {
LOG(INFO) << "Unable to record discovery phase due to null " LOG(INFO) << "Unable to record discovery phase due to null "
"current_strategy_session_"; "current_strategy_session_";
} }
} }
outgoing_connection_requests_.clear(); outgoing_connection_requests_.clear();
@@ -1174,9 +1168,8 @@ void AnalyticsRecorder::FinishDiscoveryPhaseLocked() {
bool AnalyticsRecorder::UpdateAdvertiserConnectionRequestLocked( bool AnalyticsRecorder::UpdateAdvertiserConnectionRequestLocked(
ConnectionsLog::ConnectionRequest *request) { ConnectionsLog::ConnectionRequest *request) {
if (current_advertising_phase_ == nullptr) { if (current_advertising_phase_ == nullptr) {
LOG(INFO) LOG(INFO) << "Unable to record advertiser connection request due to null "
<< "Unable to record advertiser connection request due to null " "current_advertising_phase_";
"current_advertising_phase_";
return false; return false;
} }
if (BothEndpointsRespondedLocked(request)) { if (BothEndpointsRespondedLocked(request)) {
@@ -1195,7 +1188,7 @@ bool AnalyticsRecorder::UpdateDiscovererConnectionRequestLocked(
ConnectionsLog::ConnectionRequest *request) { ConnectionsLog::ConnectionRequest *request) {
if (current_discovery_phase_ == nullptr) { if (current_discovery_phase_ == nullptr) {
LOG(INFO) << "Unable to record discoverer connection request due " LOG(INFO) << "Unable to record discoverer connection request due "
"to null current_discovery_phase_."; "to null current_discovery_phase_.";
return false; return false;
} }
if (BothEndpointsRespondedLocked(request) || if (BothEndpointsRespondedLocked(request) ||
@@ -1324,7 +1317,7 @@ void AnalyticsRecorder::FinishUpgradeAttemptLocked(
OperationResultCode operation_result_code, bool erase_item) { OperationResultCode operation_result_code, bool erase_item) {
if (current_strategy_session_ == nullptr) { if (current_strategy_session_ == nullptr) {
LOG(INFO) << "Unable to record upgrade attempt due to null " LOG(INFO) << "Unable to record upgrade attempt due to null "
"current_strategy_session_"; "current_strategy_session_";
return; return;
} }
// Add the BandwidthUpgradeAttempt in the current StrategySession. // Add the BandwidthUpgradeAttempt in the current StrategySession.
@@ -1455,9 +1448,8 @@ ConnectionsLog::Payload AnalyticsRecorder::PendingPayload::GetProtoPayload(
void AnalyticsRecorder::LogicalConnection::PhysicalConnectionEstablished( void AnalyticsRecorder::LogicalConnection::PhysicalConnectionEstablished(
Medium medium, const std::string &connection_token) { Medium medium, const std::string &connection_token) {
if (current_medium_ != UNKNOWN_MEDIUM) { if (current_medium_ != UNKNOWN_MEDIUM) {
LOG(WARNING) LOG(WARNING) << "Unexpected call to PhysicalConnectionEstablished while "
<< "Unexpected call to PhysicalConnectionEstablished while " "AnalyticsRecorder still has an active current medium.";
"AnalyticsRecorder still has an active current medium.";
} }
auto established_connection = auto established_connection =
@@ -1483,15 +1475,14 @@ void AnalyticsRecorder::LogicalConnection::PhysicalConnectionEstablished(
void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed( void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed(
Medium medium, DisconnectionReason reason, SafeDisconnectionResult result) { Medium medium, DisconnectionReason reason, SafeDisconnectionResult result) {
if (current_medium_ == UNKNOWN_MEDIUM) { if (current_medium_ == UNKNOWN_MEDIUM) {
LOG(WARNING) LOG(WARNING) << "Unexpected call to PhysicalConnectionClosed() for medium "
<< "Unexpected call to PhysicalConnectionClosed() for medium " << Medium_Name(medium)
<< Medium_Name(medium) << " while AnalyticsRecorder has no active current medium";
<< " while AnalyticsRecorder has no active current medium";
} else if (current_medium_ != medium) { } else if (current_medium_ != medium) {
LOG(WARNING) LOG(WARNING) << "Unexpected call to PhysicalConnectionClosed() for medium "
<< "Unexpected call to PhysicalConnectionClosed() for medium " << Medium_Name(medium)
<< Medium_Name(medium) << "while AnalyticsRecorder has active medium " << "while AnalyticsRecorder has active medium "
<< Medium_Name(current_medium_); << Medium_Name(current_medium_);
} }
auto it = physical_connections_.find(medium); auto it = physical_connections_.find(medium);
@@ -1506,11 +1497,11 @@ void AnalyticsRecorder::LogicalConnection::PhysicalConnectionClosed(
ConnectionsLog::EstablishedConnection *established_connection = ConnectionsLog::EstablishedConnection *established_connection =
it->second.get(); it->second.get();
if (established_connection->has_disconnection_reason()) { if (established_connection->has_disconnection_reason()) {
LOG(WARNING) LOG(WARNING) << "Unexpected call to physicalConnectionClosed() for medium "
<< "Unexpected call to physicalConnectionClosed() for medium " << Medium_Name(medium)
<< Medium_Name(medium) << " which already has disconnection reason " << " which already has disconnection reason "
<< DisconnectionReason_Name( << DisconnectionReason_Name(
established_connection->disconnection_reason()); established_connection->disconnection_reason());
return; return;
} }
FinishPhysicalConnection(established_connection, reason, result); FinishPhysicalConnection(established_connection, reason, result);
@@ -1582,7 +1573,7 @@ void AnalyticsRecorder::LogicalConnection::IncomingPayloadDone(
OperationResultCode operation_result_code) { OperationResultCode operation_result_code) {
if (current_medium_ == UNKNOWN_MEDIUM) { if (current_medium_ == UNKNOWN_MEDIUM) {
LOG(WARNING) << "Unexpected call to incomingPayloadDone() while " LOG(WARNING) << "Unexpected call to incomingPayloadDone() while "
"AnalyticsRecorder has no active current medium."; "AnalyticsRecorder has no active current medium.";
return; return;
} }
auto it = physical_connections_.find(current_medium_); auto it = physical_connections_.find(current_medium_);
@@ -1621,7 +1612,7 @@ void AnalyticsRecorder::LogicalConnection::OutgoingPayloadDone(
OperationResultCode operation_result_code) { OperationResultCode operation_result_code) {
if (current_medium_ == UNKNOWN_MEDIUM) { if (current_medium_ == UNKNOWN_MEDIUM) {
LOG(WARNING) << "Unexpected call to outgoingPayloadDone() while " LOG(WARNING) << "Unexpected call to outgoingPayloadDone() while "
"AnalyticsRecorder has no active current medium."; "AnalyticsRecorder has no active current medium.";
return; return;
} }
auto it = physical_connections_.find(current_medium_); auto it = physical_connections_.find(current_medium_);
@@ -56,12 +56,10 @@ void ThroughputRecorder::Start(PayloadType payload_type,
(payload_direction == PayloadDirection::INCOMING_PAYLOAD) ? "; Receive" (payload_direction == PayloadDirection::INCOMING_PAYLOAD) ? "; Receive"
: "; Send"; : "; Send";
LOG(INFO) << "Start TP profiling for payload_id:" << payload_id_ LOG(INFO) << "Start TP profiling for payload_id:" << payload_id_ << direction;
<< direction;
if (payload_type == PayloadType::kUnknown) { if (payload_type == PayloadType::kUnknown) {
LOG(INFO) LOG(INFO) << "Ignore ThroughputRecorder::start for Unknown Payload type";
<< "Ignore ThroughputRecorder::start for Unknown Payload type";
return; return;
} }
@@ -277,7 +275,7 @@ std::string ThroughputRecorder::ToString(PayloadType type) {
void ThroughputRecorderContainer::Shutdown() { void ThroughputRecorderContainer::Shutdown() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << __func__ LOG(INFO) << __func__
<< ". Num of Instance:" << throughput_recorders_.size(); << ". Num of Instance:" << throughput_recorders_.size();
for (auto& throughput_recorder : throughput_recorders_) { for (auto& throughput_recorder : throughput_recorders_) {
LOG(INFO) << "Stop instance: " << throughput_recorder.second; LOG(INFO) << "Stop instance: " << throughput_recorder.second;
throughput_recorder.second->Stop(); throughput_recorder.second->Stop();
@@ -297,7 +295,7 @@ ThroughputRecorder* ThroughputRecorderContainer::GetTPRecorder(
(payload_direction == PayloadDirection::INCOMING_PAYLOAD) ? "; Receive" (payload_direction == PayloadDirection::INCOMING_PAYLOAD) ? "; Receive"
: "; Send"; : "; Send";
LOG(INFO) << "Add ThroughputRecorder instance : " << instance LOG(INFO) << "Add ThroughputRecorder instance : " << instance
<< " for payload_id:" << payload_id << direction; << " for payload_id:" << payload_id << direction;
throughput_recorders_.emplace( throughput_recorders_.emplace(
std::pair<int64_t, PayloadDirection>(payload_id, payload_direction), std::pair<int64_t, PayloadDirection>(payload_id, payload_direction),
instance); instance);
@@ -317,8 +315,7 @@ void ThroughputRecorderContainer::StopTPRecorder(
std::pair<int64_t, PayloadDirection>(payload_id, payload_direction)); std::pair<int64_t, PayloadDirection>(payload_id, payload_direction));
if (it != throughput_recorders_.end()) { if (it != throughput_recorders_.end()) {
LOG(INFO) << "Found and stop/delete ThroughputRecorder instance : " LOG(INFO) << "Found and stop/delete ThroughputRecorder instance : "
<< &(it->second) << " for payload_id:" << payload_id << &(it->second) << " for payload_id:" << payload_id << direction;
<< direction;
it->second->Stop(); it->second->Stop();
delete it->second; delete it->second;
throughput_recorders_.erase( throughput_recorders_.erase(
@@ -54,9 +54,9 @@ void BaseBwuHandler::RevertInitiatorState() {
void BaseBwuHandler::RevertInitiatorState(const std::string& upgrade_service_id, void BaseBwuHandler::RevertInitiatorState(const std::string& upgrade_service_id,
const std::string& endpoint_id) { const std::string& endpoint_id) {
if (!IsInitiatorUpgradeServiceId(upgrade_service_id)) { if (!IsInitiatorUpgradeServiceId(upgrade_service_id)) {
LOG(ERROR) LOG(ERROR) << "BaseBwuHandler::RevertInitiatorState: input service ID "
<< "BaseBwuHandler::RevertInitiatorState: input service ID " << upgrade_service_id
<< upgrade_service_id << " is not an BWU initiator ID; ignoring."; << " is not an BWU initiator ID; ignoring.";
return; return;
} }
@@ -82,8 +82,7 @@ void BaseBwuHandler::RevertResponderState(const std::string& service_id) {
void BaseBwuHandler::NotifyOnIncomingConnection( void BaseBwuHandler::NotifyOnIncomingConnection(
ClientProxy* client, std::unique_ptr<IncomingSocketConnection> connection) { ClientProxy* client, std::unique_ptr<IncomingSocketConnection> connection) {
if (!incoming_connection_callback_) { if (!incoming_connection_callback_) {
LOG(WARNING) LOG(WARNING) << "Ignoring incoming connection, no callback registered";
<< "Ignoring incoming connection, no callback registered";
return; return;
} }
incoming_connection_callback_(client, std::move(connection)); incoming_connection_callback_(client, std::move(connection));
@@ -137,7 +137,7 @@ ExceptionOr<ByteArray> BaseEndpointChannel::Read(
if (read_int.result() < 0 || read_int.result() > max_allowed_read_bytes_) { if (read_int.result() < 0 || read_int.result() > max_allowed_read_bytes_) {
LOG(WARNING) << __func__ << ": Read an invalid number of bytes: " LOG(WARNING) << __func__ << ": Read an invalid number of bytes: "
<< read_int.result(); << read_int.result();
return ExceptionOr<ByteArray>(Exception::kIo); return ExceptionOr<ByteArray>(Exception::kIo);
} }
@@ -173,19 +173,18 @@ ExceptionOr<ByteArray> BaseEndpointChannel::Read(
if (parsed.ok()) { if (parsed.ok()) {
if (parser::GetFrameType(parsed.result()) == if (parser::GetFrameType(parsed.result()) ==
location::nearby::connections::V1Frame::KEEP_ALIVE) { location::nearby::connections::V1Frame::KEEP_ALIVE) {
LOG(INFO) LOG(INFO) << __func__
<< __func__ << ": Read unencrypted KEEP_ALIVE on encrypted channel.";
<< ": Read unencrypted KEEP_ALIVE on encrypted channel.";
result = ByteArray(input); result = ByteArray(input);
} else { } else {
LOG(WARNING) LOG(WARNING) << __func__
<< __func__ << ": Read unexpected unencrypted frame of type " << ": Read unexpected unencrypted frame of type "
<< parser::GetFrameType(parsed.result()); << parser::GetFrameType(parsed.result());
} }
} else { } else {
message_exception.value = parsed.exception(); message_exception.value = parsed.exception();
LOG(WARNING) LOG(WARNING) << __func__
<< __func__ << ": Unable to parse data as unencrypted message."; << ": Unable to parse data as unencrypted message.";
} }
} }
packet_meta_data.StopEncryption(); packet_meta_data.StopEncryption();
@@ -244,8 +243,8 @@ Exception BaseEndpointChannel::Write(const ByteArray& data,
size_t data_size = data_to_write->size(); size_t data_size = data_to_write->size();
if (data_size < 0 || data_size > max_allowed_read_bytes_) { if (data_size < 0 || data_size > max_allowed_read_bytes_) {
LOG(WARNING) << __func__ << ": Write an invalid number of bytes: " LOG(WARNING) << __func__
<< data_size; << ": Write an invalid number of bytes: " << data_size;
return {Exception::kIo}; return {Exception::kIo};
} }
@@ -253,20 +252,20 @@ Exception BaseEndpointChannel::Write(const ByteArray& data,
Exception write_exception = Exception write_exception =
WriteInt(writer_, static_cast<std::int32_t>(data_size)); WriteInt(writer_, static_cast<std::int32_t>(data_size));
if (write_exception.Raised()) { if (write_exception.Raised()) {
LOG(WARNING) << __func__ << ": Failed to write header: " LOG(WARNING) << __func__
<< write_exception.value; << ": Failed to write header: " << write_exception.value;
return write_exception; return write_exception;
} }
write_exception = writer_->Write(*data_to_write); write_exception = writer_->Write(*data_to_write);
if (write_exception.Raised()) { if (write_exception.Raised()) {
LOG(WARNING) << __func__ << ": Failed to write data: " LOG(WARNING) << __func__
<< write_exception.value; << ": Failed to write data: " << write_exception.value;
return write_exception; return write_exception;
} }
Exception flush_exception = writer_->Flush(); Exception flush_exception = writer_->Flush();
if (flush_exception.Raised()) { if (flush_exception.Raised()) {
LOG(WARNING) << __func__ << ": Failed to flush writer: " LOG(WARNING) << __func__
<< flush_exception.value; << ": Failed to flush writer: " << flush_exception.value;
return flush_exception; return flush_exception;
} }
packet_meta_data.StopSocketIo(); packet_meta_data.StopSocketIo();
@@ -304,7 +303,7 @@ void BaseEndpointChannel::CloseIo() {
Exception exception = reader_->Close(); Exception exception = reader_->Close();
if (!exception.Ok()) { if (!exception.Ok()) {
LOG(WARNING) << __func__ LOG(WARNING) << __func__
<< ": Exception closing reader: " << exception.value; << ": Exception closing reader: " << exception.value;
} }
} }
{ {
@@ -314,7 +313,7 @@ void BaseEndpointChannel::CloseIo() {
Exception exception = writer_->Close(); Exception exception = writer_->Close();
if (!exception.Ok()) { if (!exception.Ok()) {
LOG(WARNING) << __func__ LOG(WARNING) << __func__
<< ": Exception closing writer: " << exception.value; << ": Exception closing writer: " << exception.value;
} }
} }
} }
@@ -339,8 +338,7 @@ void BaseEndpointChannel::Close(
void BaseEndpointChannel::Close( void BaseEndpointChannel::Close(
location::nearby::proto::connections::DisconnectionReason reason, location::nearby::proto::connections::DisconnectionReason reason,
SafeDisconnectionResult result) { SafeDisconnectionResult result) {
LOG(INFO) << __func__ LOG(INFO) << __func__ << ": Closing endpoint channel, reason: " << reason;
<< ": Closing endpoint channel, reason: " << reason;
Close(); Close();
if (analytics_recorder_ != nullptr && !endpoint_id_.empty()) { if (analytics_recorder_ != nullptr && !endpoint_id_.empty()) {
@@ -477,8 +475,8 @@ void BaseEndpointChannel::BlockUntilUnpaused() {
while (is_paused_) { while (is_paused_) {
Exception wait_succeeded = is_paused_cond_.Wait(); Exception wait_succeeded = is_paused_cond_.Wait();
if (!wait_succeeded.Ok()) { if (!wait_succeeded.Ok()) {
LOG(WARNING) << __func__ << ": Failure waiting to unpause: " LOG(WARNING) << __func__
<< wait_succeeded.value; << ": Failure waiting to unpause: " << wait_succeeded.value;
return; return;
} }
} }
@@ -98,7 +98,7 @@ std::function<void(const ByteArray&)> MakeDataMonitor(const std::string& label,
*capture += s; *capture += s;
} }
LOG(INFO) << "source='" << label << "'" LOG(INFO) << "source='" << label << "'"
<< "; message='" << s << "'"; << "; message='" << s << "'";
}; };
} }
+174 -208
View File
@@ -130,12 +130,12 @@ BasePcpHandler::~BasePcpHandler() {
void BasePcpHandler::Shutdown() { void BasePcpHandler::Shutdown() {
if (closed_.Set(true)) return; if (closed_.Set(true)) return;
LOG(INFO) << "Initiating shutdown of BasePcpHandler(" LOG(INFO) << "Initiating shutdown of BasePcpHandler(" << strategy_.GetName()
<< strategy_.GetName() << ")"; << ")";
DisconnectFromEndpointManager(); DisconnectFromEndpointManager();
// Stop all the ongoing Runnables (as gracefully as possible). // Stop all the ongoing Runnables (as gracefully as possible).
LOG(INFO) << "BasePcpHandler(" << strategy_.GetName() LOG(INFO) << "BasePcpHandler(" << strategy_.GetName()
<< ") is bringing down executors."; << ") is bringing down executors.";
encryption_runner_.Shutdown(); encryption_runner_.Shutdown();
@@ -144,14 +144,13 @@ void BasePcpHandler::Shutdown() {
serial_executor_.Shutdown(); serial_executor_.Shutdown();
alarm_executor_.Shutdown(); alarm_executor_.Shutdown();
LOG(INFO) << "BasePcpHandler(" << strategy_.GetName() LOG(INFO) << "BasePcpHandler(" << strategy_.GetName() << ") has shut down.";
<< ") has shut down.";
} }
void BasePcpHandler::DisconnectFromEndpointManager() { void BasePcpHandler::DisconnectFromEndpointManager() {
if (stop_.Set(true)) return; if (stop_.Set(true)) return;
LOG(INFO) << "BasePcpHandler(" << strategy_.GetName() LOG(INFO) << "BasePcpHandler(" << strategy_.GetName()
<< ") unregister from EPM."; << ") unregister from EPM.";
// Unregister ourselves from EPM message dispatcher. // Unregister ourselves from EPM message dispatcher.
endpoint_manager_->UnregisterFrameProcessor(V1Frame::CONNECTION_RESPONSE, endpoint_manager_->UnregisterFrameProcessor(V1Frame::CONNECTION_RESPONSE,
this); this);
@@ -228,8 +227,7 @@ Status BasePcpHandler::StartAdvertising(
advertising_options.CompatibleOptions(); advertising_options.CompatibleOptions();
StripOutUnavailableMediums(compatible_advertising_options); StripOutUnavailableMediums(compatible_advertising_options);
LOG(INFO) << "StartAdvertising with supported mediums: " LOG(INFO) << "StartAdvertising with supported mediums: "
<< GetStringValueOfSupportedMediums( << GetStringValueOfSupportedMediums(compatible_advertising_options);
compatible_advertising_options);
RunOnPcpHandlerThread( RunOnPcpHandlerThread(
"start-advertising", "start-advertising",
@@ -297,7 +295,7 @@ Status BasePcpHandler::StartAdvertising(
void BasePcpHandler::StopAdvertising(ClientProxy* client) { void BasePcpHandler::StopAdvertising(ClientProxy* client) {
LOG(INFO) << "StopAdvertising local_endpoint_id=" LOG(INFO) << "StopAdvertising local_endpoint_id="
<< client->GetLocalEndpointId(); << client->GetLocalEndpointId();
CountDownLatch latch(1); CountDownLatch latch(1);
RunOnPcpHandlerThread("stop-advertising", RunOnPcpHandlerThread("stop-advertising",
[this, client, &latch]() RUN_ON_PCP_HANDLER_THREAD() { [this, client, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
@@ -396,8 +394,7 @@ BooleanMediumSelector BasePcpHandler::ComputeIntersectionOfSupportedMediums(
if (pending_connection_info.is_incoming) { if (pending_connection_info.is_incoming) {
for (auto medium : their_mediums) { for (auto medium : their_mediums) {
LOG(INFO) << "Their supported medium name: " LOG(INFO) << "Their supported medium name: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium);
medium);
} }
} else { } else {
LOG(INFO) LOG(INFO)
@@ -407,8 +404,7 @@ BooleanMediumSelector BasePcpHandler::ComputeIntersectionOfSupportedMediums(
for (Medium my_medium : GetConnectionMediumsByPriority()) { for (Medium my_medium : GetConnectionMediumsByPriority()) {
LOG(INFO) << "Our supported medium name: " LOG(INFO) << "Our supported medium name: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(my_medium);
my_medium);
if (std::find(their_mediums.begin(), their_mediums.end(), my_medium) != if (std::find(their_mediums.begin(), their_mediums.end(), my_medium) !=
their_mediums.end()) { their_mediums.end()) {
// We use advertising options as a proxy to whether or not the local // We use advertising options as a proxy to whether or not the local
@@ -450,8 +446,7 @@ Status BasePcpHandler::StartDiscovery(ClientProxy* client,
DiscoveryOptions stripped_discovery_options = discovery_options; DiscoveryOptions stripped_discovery_options = discovery_options;
StripOutUnavailableMediums(stripped_discovery_options); StripOutUnavailableMediums(stripped_discovery_options);
LOG(INFO) << "StartDiscovery with supported mediums:" LOG(INFO) << "StartDiscovery with supported mediums:"
<< GetStringValueOfSupportedMediums( << GetStringValueOfSupportedMediums(stripped_discovery_options);
stripped_discovery_options);
RunOnPcpHandlerThread( RunOnPcpHandlerThread(
"start-discovery", "start-discovery",
[this, client, service_id, stripped_discovery_options, [this, client, service_id, stripped_discovery_options,
@@ -529,11 +524,11 @@ Status BasePcpHandler::WaitForResult(const std::string& method_name,
ExceptionOr<Status> result = future->Get(); ExceptionOr<Status> result = future->Get();
if (!result.ok()) { if (!result.ok()) {
LOG(INFO) << "Future:[" << method_name LOG(INFO) << "Future:[" << method_name
<< "] completed with exception:" << result.exception(); << "] completed with exception:" << result.exception();
return {Status::kError}; return {Status::kError};
} }
LOG(INFO) << "Future:[" << method_name LOG(INFO) << "Future:[" << method_name
<< "] completed with status:" << result.result().value; << "] completed with status:" << result.result().value;
return result.result(); return result.result();
} }
@@ -541,7 +536,7 @@ void BasePcpHandler::RunOnPcpHandlerThread(const std::string& name,
Runnable runnable) { Runnable runnable) {
if (closed_.Get()) { if (closed_.Get()) {
LOG(WARNING) << "Skip to run PCP Handler task " << name LOG(WARNING) << "Skip to run PCP Handler task " << name
<< " due to PCP Handler is closed"; << " due to PCP Handler is closed";
return; return;
} }
@@ -659,14 +654,12 @@ void BasePcpHandler::OnEncryptionSuccessRunnableV3(
// TODO(b/305004353): Authenticate the connection in the responder role for // TODO(b/305004353): Authenticate the connection in the responder role for
// outgoing connections. // outgoing connections.
if (!pending_connection_info.is_incoming) { if (!pending_connection_info.is_incoming) {
LOG(ERROR) << __func__ LOG(ERROR) << __func__ << ": only outgoing connections are supported";
<< ": only outgoing connections are supported";
return; return;
} }
VLOG(1) VLOG(1) << __func__
<< __func__ << ": beginning authentication to the remote device as an initiator";
<< ": beginning authentication to the remote device as an initiator";
ConnectionsAuthenticationTransport connections_authentication_transport = ConnectionsAuthenticationTransport connections_authentication_transport =
ConnectionsAuthenticationTransport(endpoint_channel); ConnectionsAuthenticationTransport(endpoint_channel);
pending_connection_info.authentication_status = pending_connection_info.authentication_status =
@@ -675,8 +668,8 @@ void BasePcpHandler::OnEncryptionSuccessRunnableV3(
/*shared_secret=*/auth_token, /*shared_secret=*/auth_token,
/*authentication_transport=*/connections_authentication_transport); /*authentication_transport=*/connections_authentication_transport);
LOG(INFO) << __func__ << ": authentication result = " LOG(INFO) << __func__ << ": authentication result = "
<< AuthenticationStatusToString( << AuthenticationStatusToString(
pending_connection_info.authentication_status); pending_connection_info.authentication_status);
RegisterDeviceAfterEncryptionSuccess( RegisterDeviceAfterEncryptionSuccess(
/*endpoint_id=*/remote_device.GetEndpointId(), /*endpoint_id=*/remote_device.GetEndpointId(),
@@ -727,9 +720,8 @@ void BasePcpHandler::RegisterDeviceAfterEncryptionSuccess(
pending_connection_info.SetCryptoContext(std::move(ukey2)); pending_connection_info.SetCryptoContext(std::move(ukey2));
pending_connection_info.connection_token = pending_connection_info.connection_token =
GetHashedConnectionToken(raw_auth_token); GetHashedConnectionToken(raw_auth_token);
LOG(INFO) LOG(INFO) << "Register encrypted connection; wait for response; endpoint_id="
<< "Register encrypted connection; wait for response; endpoint_id=" << endpoint_id;
<< endpoint_id;
// Set ourselves up so that we receive all acceptance/rejection messages // Set ourselves up so that we receive all acceptance/rejection messages
endpoint_manager_->RegisterFrameProcessor(V1Frame::CONNECTION_RESPONSE, this); endpoint_manager_->RegisterFrameProcessor(V1Frame::CONNECTION_RESPONSE, this);
@@ -784,8 +776,8 @@ void BasePcpHandler::OnEncryptionFailureRunnable(
// it too by accident. // it too by accident.
if (*endpoint_channel != *pending_connection_info.channel) { if (*endpoint_channel != *pending_connection_info.channel) {
LOG(INFO) << "Not destroying channel [mismatch]: passed=" LOG(INFO) << "Not destroying channel [mismatch]: passed="
<< endpoint_channel->GetName() << "; expected=" << endpoint_channel->GetName()
<< pending_connection_info.channel->GetName(); << "; expected=" << pending_connection_info.channel->GetName();
return; return;
} }
@@ -824,11 +816,11 @@ ConnectionInfo BasePcpHandler::FillConnectionInfo(
connection_info.medium_role.emplace(medium_role_info); connection_info.medium_role.emplace(medium_role_info);
} }
LOG(INFO) << "Query for WIFI information: is_supports_5_ghz=" LOG(INFO) << "Query for WIFI information: is_supports_5_ghz="
<< connection_info.supports_5_ghz << connection_info.supports_5_ghz
<< "; bssid=" << connection_info.bssid << "; bssid=" << connection_info.bssid
<< "; ap_frequency=" << connection_info.ap_frequency << "; ap_frequency=" << connection_info.ap_frequency
<< "Mhz; ip_address in bytes format=" << "Mhz; ip_address in bytes format="
<< absl::BytesToHexString(connection_info.ip_address); << absl::BytesToHexString(connection_info.ip_address);
} }
connection_info.supported_mediums = connection_info.supported_mediums =
GetSupportedConnectionMediumsByPriority(connection_options); GetSupportedConnectionMediumsByPriority(connection_options);
@@ -861,8 +853,8 @@ Status BasePcpHandler::RequestConnection(
DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id); DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id);
if (endpoint == nullptr) { if (endpoint == nullptr) {
LOG(INFO) LOG(INFO) << "Discovered endpoint not found: endpoint_id="
<< "Discovered endpoint not found: endpoint_id=" << endpoint_id; << endpoint_id;
result->Set({Status::kEndpointUnknown}); result->Set({Status::kEndpointUnknown});
return; return;
} }
@@ -873,9 +865,8 @@ Status BasePcpHandler::RequestConnection(
if (AppendRemoteBluetoothMacAddressEndpoint( if (AppendRemoteBluetoothMacAddressEndpoint(
endpoint_id, remote_bluetooth_mac_address, endpoint_id, remote_bluetooth_mac_address,
client->GetDiscoveryOptions())) client->GetDiscoveryOptions()))
LOG(INFO) LOG(INFO) << "Appended remote Bluetooth MAC Address endpoint ["
<< "Appended remote Bluetooth MAC Address endpoint [" << remote_bluetooth_mac_address << "]";
<< remote_bluetooth_mac_address << "]";
} }
if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions())) if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions()))
@@ -899,8 +890,8 @@ Status BasePcpHandler::RequestConnection(
Medium channel_medium = Medium channel_medium =
channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM; channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
if (channel == nullptr) { if (channel == nullptr) {
LOG(INFO) LOG(INFO) << "Endpoint channel not available: endpoint_id="
<< "Endpoint channel not available: endpoint_id=" << endpoint_id; << endpoint_id;
ProcessPreConnectionInitiationFailure( ProcessPreConnectionInitiationFailure(
client, channel_medium, endpoint_id, channel.get(), client, channel_medium, endpoint_id, channel.get(),
/* is_incoming = */ false, start_time, connect_impl_result.status, /* is_incoming = */ false, start_time, connect_impl_result.status,
@@ -908,10 +899,9 @@ Status BasePcpHandler::RequestConnection(
return; return;
} }
LOG(INFO) LOG(INFO) << "In requestConnection(), wrote ConnectionRequestFrame "
<< "In requestConnection(), wrote ConnectionRequestFrame " "to endpoint_id="
"to endpoint_id=" << endpoint_id;
<< endpoint_id;
client->OnRequestConnection(GetStrategy(), endpoint_id, client->OnRequestConnection(GetStrategy(), endpoint_id,
connection_options); connection_options);
@@ -925,7 +915,7 @@ Status BasePcpHandler::RequestConnection(
connection_info, channel.get()); connection_info, channel.get());
if (!write_exception.Ok()) { if (!write_exception.Ok()) {
LOG(INFO) << "Failed to send connection request: endpoint_id=" LOG(INFO) << "Failed to send connection request: endpoint_id="
<< endpoint_id; << endpoint_id;
ProcessPreConnectionInitiationFailure( ProcessPreConnectionInitiationFailure(
client, channel_medium, endpoint_id, channel.get(), client, channel_medium, endpoint_id, channel.get(),
/* is_incoming = */ false, start_time, {Status::kEndpointIoError}, /* is_incoming = */ false, start_time, {Status::kEndpointIoError},
@@ -936,7 +926,7 @@ Status BasePcpHandler::RequestConnection(
} }
LOG(INFO) << "Adding connection to pending set: endpoint_id=" LOG(INFO) << "Adding connection to pending set: endpoint_id="
<< endpoint_id; << endpoint_id;
// We've successfully connected to the device, and are now about to jump // We've successfully connected to the device, and are now about to jump
// on to the EncryptionRunner thread to start running our encryption // on to the EncryptionRunner thread to start running our encryption
@@ -965,19 +955,19 @@ Status BasePcpHandler::RequestConnection(
.first->second.channel.get(); .first->second.channel.get();
LOG(INFO) << "Initiating secure connection: endpoint_id=" LOG(INFO) << "Initiating secure connection: endpoint_id="
<< endpoint_id; << endpoint_id;
// Next, we'll set up encryption. When it's done, our future will return // Next, we'll set up encryption. When it's done, our future will return
// and RequestConnection() will finish. // and RequestConnection() will finish.
encryption_runner_.StartClient(client, endpoint_id, endpoint_channel, encryption_runner_.StartClient(client, endpoint_id, endpoint_channel,
GetResultListener()); GetResultListener());
}); });
LOG(INFO) << "Waiting for connection to complete: endpoint_id=" LOG(INFO) << "Waiting for connection to complete: endpoint_id="
<< endpoint_id; << endpoint_id;
auto status = auto status =
WaitForResult(absl::StrCat("RequestConnection(", endpoint_id, ")"), WaitForResult(absl::StrCat("RequestConnection(", endpoint_id, ")"),
client->GetClientId(), result.get()); client->GetClientId(), result.get());
LOG(INFO) << "Wait is complete: endpoint_id=" << endpoint_id LOG(INFO) << "Wait is complete: endpoint_id=" << endpoint_id
<< "; status=" << status.value; << "; status=" << status.value;
return status; return status;
} }
@@ -1003,8 +993,8 @@ Status BasePcpHandler::RequestConnectionV3(
DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id); DiscoveredEndpoint* endpoint = GetDiscoveredEndpoint(endpoint_id);
if (endpoint == nullptr) { if (endpoint == nullptr) {
LOG(INFO) LOG(INFO) << "Discovered endpoint not found: endpoint_id="
<< "Discovered endpoint not found: endpoint_id=" << endpoint_id; << endpoint_id;
result->Set({Status::kEndpointUnknown}); result->Set({Status::kEndpointUnknown});
return; return;
} }
@@ -1015,9 +1005,8 @@ Status BasePcpHandler::RequestConnectionV3(
if (AppendRemoteBluetoothMacAddressEndpoint( if (AppendRemoteBluetoothMacAddressEndpoint(
endpoint_id, remote_bluetooth_mac_address, endpoint_id, remote_bluetooth_mac_address,
client->GetDiscoveryOptions())) client->GetDiscoveryOptions()))
LOG(INFO) LOG(INFO) << "Appended remote Bluetooth MAC Address endpoint ["
<< "Appended remote Bluetooth MAC Address endpoint [" << remote_bluetooth_mac_address << "]";
<< remote_bluetooth_mac_address << "]";
} }
if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions())) if (AppendWebRTCEndpoint(endpoint_id, client->GetDiscoveryOptions()))
@@ -1031,11 +1020,10 @@ Status BasePcpHandler::RequestConnectionV3(
if (!MediumSupportedByClientOptions(connect_endpoint->medium, if (!MediumSupportedByClientOptions(connect_endpoint->medium,
connection_options)) connection_options))
continue; continue;
LOG(INFO) LOG(INFO) << "Try to connect with endpoint(id=" << endpoint_id
<< "Try to connect with endpoint(id=" << endpoint_id << ") by Medium: "
<< ") by Medium: " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( connect_endpoint->medium);
connect_endpoint->medium);
connect_impl_result = ConnectImpl(client, connect_endpoint); connect_impl_result = ConnectImpl(client, connect_endpoint);
if (connect_impl_result.status.Ok()) { if (connect_impl_result.status.Ok()) {
channel = std::move(connect_impl_result.endpoint_channel); channel = std::move(connect_impl_result.endpoint_channel);
@@ -1046,8 +1034,8 @@ Status BasePcpHandler::RequestConnectionV3(
Medium channel_medium = Medium channel_medium =
channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM; channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
if (channel == nullptr) { if (channel == nullptr) {
LOG(INFO) LOG(INFO) << "Endpoint channel not available: endpoint_id="
<< "Endpoint channel not available: endpoint_id=" << endpoint_id; << endpoint_id;
ProcessPreConnectionInitiationFailure( ProcessPreConnectionInitiationFailure(
client, channel_medium, endpoint_id, channel.get(), client, channel_medium, endpoint_id, channel.get(),
/* is_incoming = */ false, start_time, connect_impl_result.status, /* is_incoming = */ false, start_time, connect_impl_result.status,
@@ -1055,10 +1043,9 @@ Status BasePcpHandler::RequestConnectionV3(
return; return;
} }
LOG(INFO) LOG(INFO) << "In requestConnectionV3(), wrote ConnectionRequestFrame "
<< "In requestConnectionV3(), wrote ConnectionRequestFrame " "to endpoint_id="
"to endpoint_id=" << endpoint_id;
<< endpoint_id;
client->OnRequestConnection(GetStrategy(), endpoint_id, client->OnRequestConnection(GetStrategy(), endpoint_id,
connection_options); connection_options);
@@ -1073,7 +1060,7 @@ Status BasePcpHandler::RequestConnectionV3(
if (!write_exception.Ok()) { if (!write_exception.Ok()) {
LOG(INFO) << "Failed to send connection request: endpoint_id=" LOG(INFO) << "Failed to send connection request: endpoint_id="
<< endpoint_id; << endpoint_id;
ProcessPreConnectionInitiationFailure( ProcessPreConnectionInitiationFailure(
client, channel_medium, endpoint_id, channel.get(), client, channel_medium, endpoint_id, channel.get(),
/* is_incoming = */ false, start_time, {Status::kEndpointIoError}, /* is_incoming = */ false, start_time, {Status::kEndpointIoError},
@@ -1084,7 +1071,7 @@ Status BasePcpHandler::RequestConnectionV3(
} }
LOG(INFO) << "Adding connection to pending set: endpoint_id=" LOG(INFO) << "Adding connection to pending set: endpoint_id="
<< endpoint_id; << endpoint_id;
// We've successfully connected to the device, and are now about to jump // We've successfully connected to the device, and are now about to jump
// on to the EncryptionRunner thread to start running our encryption // on to the EncryptionRunner thread to start running our encryption
@@ -1113,7 +1100,7 @@ Status BasePcpHandler::RequestConnectionV3(
.first->second.channel.get(); .first->second.channel.get();
LOG(INFO) << "Initiating secure connection: endpoint_id=" LOG(INFO) << "Initiating secure connection: endpoint_id="
<< endpoint_id; << endpoint_id;
// Next, we'll set up encryption and authenticate the remote device. // Next, we'll set up encryption and authenticate the remote device.
// When it's done, our future will return and RequestConnectionV3() // When it's done, our future will return and RequestConnectionV3()
// will finish. // will finish.
@@ -1123,12 +1110,12 @@ Status BasePcpHandler::RequestConnectionV3(
remote_device, *endpoint_channel)); remote_device, *endpoint_channel));
}); });
LOG(INFO) << "Waiting for connection to complete: endpoint_id=" LOG(INFO) << "Waiting for connection to complete: endpoint_id="
<< endpoint_id; << endpoint_id;
auto status = auto status =
WaitForResult(absl::StrCat("RequestConnectionV3(", endpoint_id, ")"), WaitForResult(absl::StrCat("RequestConnectionV3(", endpoint_id, ")"),
client->GetClientId(), result.get()); client->GetClientId(), result.get());
LOG(INFO) << "Wait is complete: endpoint_id=" << endpoint_id LOG(INFO) << "Wait is complete: endpoint_id=" << endpoint_id
<< "; status=" << status.value; << "; status=" << status.value;
return status; return status;
} }
@@ -1466,8 +1453,8 @@ Status BasePcpHandler::AcceptConnection(ClientProxy* client,
channel_manager_->GetChannelForEndpoint(endpoint_id); channel_manager_->GetChannelForEndpoint(endpoint_id);
if (channel == nullptr) { if (channel == nullptr) {
LOG(ERROR) << "Channel destroyed before Accept; bring down " LOG(ERROR) << "Channel destroyed before Accept; bring down "
"connection: endpoint_id=" "connection: endpoint_id="
<< endpoint_id; << endpoint_id;
ProcessPreConnectionResultFailure( ProcessPreConnectionResultFailure(
client, endpoint_id, /* should_call_disconnect_endpoint= */ true, client, endpoint_id, /* should_call_disconnect_endpoint= */ true,
DisconnectionReason::IO_ERROR); DisconnectionReason::IO_ERROR);
@@ -1480,9 +1467,8 @@ Status BasePcpHandler::AcceptConnection(ClientProxy* client,
Status::kSuccess, client->GetLocalOsInfo(), Status::kSuccess, client->GetLocalOsInfo(),
client->GetLocalMultiplexSocketBitmask())); client->GetLocalMultiplexSocketBitmask()));
if (!write_exception.Ok()) { if (!write_exception.Ok()) {
LOG(INFO) LOG(INFO) << "AcceptConnection: failed to send response: endpoint_id="
<< "AcceptConnection: failed to send response: endpoint_id=" << endpoint_id;
<< endpoint_id;
ProcessPreConnectionResultFailure( ProcessPreConnectionResultFailure(
client, endpoint_id, /* should_call_disconnect_endpoint= */ true, client, endpoint_id, /* should_call_disconnect_endpoint= */ true,
DisconnectionReason::IO_ERROR); DisconnectionReason::IO_ERROR);
@@ -1491,7 +1477,7 @@ Status BasePcpHandler::AcceptConnection(ClientProxy* client,
} }
LOG(INFO) << "AcceptConnection: accepting locally: endpoint_id=" LOG(INFO) << "AcceptConnection: accepting locally: endpoint_id="
<< endpoint_id; << endpoint_id;
connection_info.LocalEndpointAcceptedConnection( connection_info.LocalEndpointAcceptedConnection(
endpoint_id, std::move(payload_listener)); endpoint_id, std::move(payload_listener));
EvaluateConnectionResult(client, endpoint_id, EvaluateConnectionResult(client, endpoint_id,
@@ -1543,9 +1529,8 @@ Status BasePcpHandler::RejectConnection(ClientProxy* client,
Status::kConnectionRejected, client->GetLocalOsInfo(), Status::kConnectionRejected, client->GetLocalOsInfo(),
client->GetLocalMultiplexSocketBitmask())); client->GetLocalMultiplexSocketBitmask()));
if (!write_exception.Ok()) { if (!write_exception.Ok()) {
LOG(INFO) LOG(INFO) << "RejectConnection: failed to send response: endpoint_id="
<< "RejectConnection: failed to send response: endpoint_id=" << endpoint_id;
<< endpoint_id;
ProcessPreConnectionResultFailure( ProcessPreConnectionResultFailure(
client, endpoint_id, /* should_call_disconnect_endpoint= */ true, client, endpoint_id, /* should_call_disconnect_endpoint= */ true,
DisconnectionReason::IO_ERROR); DisconnectionReason::IO_ERROR);
@@ -1554,7 +1539,7 @@ Status BasePcpHandler::RejectConnection(ClientProxy* client,
} }
LOG(INFO) << "RejectConnection: rejecting locally: endpoint_id=" LOG(INFO) << "RejectConnection: rejecting locally: endpoint_id="
<< endpoint_id; << endpoint_id;
connection_info.LocalEndpointRejectedConnection(endpoint_id); connection_info.LocalEndpointRejectedConnection(endpoint_id);
EvaluateConnectionResult(client, endpoint_id, EvaluateConnectionResult(client, endpoint_id,
false /* can_close_immediately */); false /* can_close_immediately */);
@@ -1573,13 +1558,11 @@ void BasePcpHandler::OnIncomingFrame(
RunOnPcpHandlerThread( RunOnPcpHandlerThread(
"incoming-frame", "incoming-frame",
[this, client, endpoint_id, frame, &latch]() RUN_ON_PCP_HANDLER_THREAD() { [this, client, endpoint_id, frame, &latch]() RUN_ON_PCP_HANDLER_THREAD() {
LOG(INFO) << "OnConnectionResponse: endpoint_id=" LOG(INFO) << "OnConnectionResponse: endpoint_id=" << endpoint_id;
<< endpoint_id;
if (client->HasRemoteEndpointResponded(endpoint_id)) { if (client->HasRemoteEndpointResponded(endpoint_id)) {
LOG(INFO) LOG(INFO) << "OnConnectionResponse: already handled; endpoint_id="
<< "OnConnectionResponse: already handled; endpoint_id=" << endpoint_id;
<< endpoint_id;
return; return;
} }
@@ -1597,14 +1580,13 @@ void BasePcpHandler::OnIncomingFrame(
accepted = connection_response.status() == Status::kSuccess; accepted = connection_response.status() == Status::kSuccess;
} }
if (accepted) { if (accepted) {
LOG(INFO) LOG(INFO) << "OnConnectionResponse: remote accepted; endpoint_id="
<< "OnConnectionResponse: remote accepted; endpoint_id=" << endpoint_id;
<< endpoint_id;
client->RemoteEndpointAcceptedConnection(endpoint_id); client->RemoteEndpointAcceptedConnection(endpoint_id);
} else { } else {
LOG(INFO) LOG(INFO) << "OnConnectionResponse: remote rejected; endpoint_id="
<< "OnConnectionResponse: remote rejected; endpoint_id=" << endpoint_id
<< endpoint_id << "; status=" << connection_response.status(); << "; status=" << connection_response.status();
client->RemoteEndpointRejectedConnection(endpoint_id); client->RemoteEndpointRejectedConnection(endpoint_id);
} }
@@ -1618,10 +1600,9 @@ void BasePcpHandler::OnIncomingFrame(
} }
if (connection_response.has_safe_to_disconnect_version()) { if (connection_response.has_safe_to_disconnect_version()) {
LOG(INFO) LOG(INFO) << "[safe-to-disconnect]: endpoint_id=" << endpoint_id
<< "[safe-to-disconnect]: endpoint_id=" << endpoint_id << "; Version = "
<< "; Version = " << connection_response.safe_to_disconnect_version();
<< connection_response.safe_to_disconnect_version();
client->SetRemoteSafeToDisconnectVersion( client->SetRemoteSafeToDisconnectVersion(
endpoint_id, connection_response.safe_to_disconnect_version()); endpoint_id, connection_response.safe_to_disconnect_version());
} }
@@ -1671,9 +1652,9 @@ void BasePcpHandler::OnEndpointFound(
// Check if we've seen this endpoint ID before. // Check if we've seen this endpoint ID before.
std::string& endpoint_id = endpoint->endpoint_id; std::string& endpoint_id = endpoint->endpoint_id;
LOG(INFO) << "OnEndpointFound: id=" << endpoint_id << ", medium=" LOG(INFO) << "OnEndpointFound: id=" << endpoint_id << ", medium="
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
endpoint->medium) endpoint->medium)
<< " [enter]"; << " [enter]";
MutexLock lock(&discovered_endpoint_mutex_); MutexLock lock(&discovered_endpoint_mutex_);
auto range = discovered_endpoints_.equal_range(endpoint->endpoint_id); auto range = discovered_endpoints_.equal_range(endpoint->endpoint_id);
bool is_range_empty = range.first == range.second; bool is_range_empty = range.first == range.second;
@@ -1685,8 +1666,8 @@ void BasePcpHandler::OnEndpointFound(
// handle it to avoid device refresh between different mediums. // handle it to avoid device refresh between different mediums.
if (discovered_endpoint->medium == endpoint->medium) { if (discovered_endpoint->medium == endpoint->medium) {
LOG(INFO) << "Ignore the dup endpoint info on medium " LOG(INFO) << "Ignore the dup endpoint info on medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
endpoint->medium); endpoint->medium);
return; return;
} }
} else { } else {
@@ -1695,9 +1676,9 @@ void BasePcpHandler::OnEndpointFound(
// we should reset discovered endpoints of the endpoint ID, and use the // we should reset discovered endpoints of the endpoint ID, and use the
// new endpoint info and medium as discovered endpoint. // new endpoint info and medium as discovered endpoint.
LOG(INFO) << "Endpoint info of endpoint " << endpoint_id LOG(INFO) << "Endpoint info of endpoint " << endpoint_id
<< " changed on medium " << " changed on medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
endpoint->medium); endpoint->medium);
// Report endpoint lost // Report endpoint lost
client->OnEndpointLost(endpoint->service_id, endpoint->endpoint_id); client->OnEndpointLost(endpoint->service_id, endpoint->endpoint_id);
// Reset discovered endpoints // Reset discovered endpoints
@@ -1715,8 +1696,8 @@ void BasePcpHandler::OnEndpointFound(
} }
if (discovered_endpoint->medium == endpoint->medium) { if (discovered_endpoint->medium == endpoint->medium) {
LOG(INFO) << "Ignore the dup endpoint info on medium " LOG(INFO) << "Ignore the dup endpoint info on medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
endpoint->medium); endpoint->medium);
return; return;
} }
} }
@@ -1726,10 +1707,10 @@ void BasePcpHandler::OnEndpointFound(
discovered_endpoints_.emplace(endpoint_id, std::move(endpoint)) discovered_endpoints_.emplace(endpoint_id, std::move(endpoint))
->second.get(); ->second.get();
LOG(INFO) << "Adding new medium for endpoint: endpoint_id=" LOG(INFO) << "Adding new medium for endpoint: endpoint_id=" << endpoint_id
<< endpoint_id << "; medium=" << "; medium="
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
owned_endpoint->medium); owned_endpoint->medium);
// Range is empty: this is the first endpoint we discovered so far. // Range is empty: this is the first endpoint we discovered so far.
// Report this endpoint_id to client. // Report this endpoint_id to client.
@@ -1744,16 +1725,15 @@ void BasePcpHandler::OnEndpointFound(
void BasePcpHandler::OnEndpointLost( void BasePcpHandler::OnEndpointLost(
ClientProxy* client, const BasePcpHandler::DiscoveredEndpoint& endpoint) { ClientProxy* client, const BasePcpHandler::DiscoveredEndpoint& endpoint) {
// Look up the DiscoveredEndpoint we have in our cache. // Look up the DiscoveredEndpoint we have in our cache.
LOG(INFO) << "OnEndpointLost: id=" << endpoint.endpoint_id LOG(INFO) << "OnEndpointLost: id=" << endpoint.endpoint_id << " on medium="
<< " on medium=" << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( endpoint.medium);
endpoint.medium);
MutexLock lock(&discovered_endpoint_mutex_); MutexLock lock(&discovered_endpoint_mutex_);
auto range = discovered_endpoints_.equal_range(endpoint.endpoint_id); auto range = discovered_endpoints_.equal_range(endpoint.endpoint_id);
bool is_range_empty = range.first == range.second; bool is_range_empty = range.first == range.second;
if (is_range_empty) { if (is_range_empty) {
LOG(INFO) << "No previous endpoint (nothing to lose): endpoint_id=" LOG(INFO) << "No previous endpoint (nothing to lose): endpoint_id="
<< endpoint.endpoint_id; << endpoint.endpoint_id;
return; return;
} }
int count = discovered_endpoints_.count(endpoint.endpoint_id); int count = discovered_endpoints_.count(endpoint.endpoint_id);
@@ -1769,15 +1749,14 @@ void BasePcpHandler::OnEndpointLost(
// new info and are just now figuring out that we lost the old info. // new info and are just now figuring out that we lost the old info.
if (discovered_endpoint->endpoint_info != endpoint.endpoint_info) { if (discovered_endpoint->endpoint_info != endpoint.endpoint_info) {
LOG(INFO) << "Previous endpoint name mismatch; passed=" LOG(INFO) << "Previous endpoint name mismatch; passed="
<< absl::BytesToHexString(endpoint.endpoint_info.data()) << absl::BytesToHexString(endpoint.endpoint_info.data())
<< "; expected=" << "; expected="
<< absl::BytesToHexString( << absl::BytesToHexString(
discovered_endpoint->endpoint_info.data()); discovered_endpoint->endpoint_info.data());
} }
LOG(INFO) << "Erase Endpoint " << endpoint.endpoint_id LOG(INFO) << "Erase Endpoint " << endpoint.endpoint_id << " on Medium "
<< " on Medium " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( discovered_endpoint->medium);
discovered_endpoint->medium);
if (--count == 0) { if (--count == 0) {
client->OnEndpointLost(endpoint.service_id, endpoint.endpoint_id); client->OnEndpointLost(endpoint.service_id, endpoint.endpoint_id);
} }
@@ -1802,8 +1781,7 @@ void BasePcpHandler::OnInstantLost(ClientProxy* client,
} }
} }
LOG(INFO) << "Reported lost endpoint " << endpoint_id LOG(INFO) << "Reported lost endpoint " << endpoint_id << " on all mediums.";
<< " on all mediums.";
} }
Status BasePcpHandler::UpdateAdvertisingOptions( Status BasePcpHandler::UpdateAdvertisingOptions(
@@ -1895,11 +1873,11 @@ bool BasePcpHandler::IsPreferred(
for (const auto& medium : mediums) { for (const auto& medium : mediums) {
absl::StrAppend(&medium_string, medium, "; "); absl::StrAppend(&medium_string, medium, "; ");
} }
LOG(ERROR) << "Failed to find either " << new_endpoint.medium LOG(ERROR) << "Failed to find either " << new_endpoint.medium << " or "
<< " or " << old_endpoint.medium << old_endpoint.medium
<< " in the list of locally supported mediums despite " << " in the list of locally supported mediums despite "
"expecting to find both, when deciding which medium " "expecting to find both, when deciding which medium "
<< medium_string << " is preferred."; << medium_string << " is preferred.";
return false; return false;
} }
@@ -1916,10 +1894,10 @@ Exception BasePcpHandler::OnIncomingConnection(
if (!client->IsAdvertising() && if (!client->IsAdvertising() &&
!client->IsListeningForIncomingConnections()) { !client->IsListeningForIncomingConnections()) {
LOG(WARNING) << "Ignoring incoming connection on medium " LOG(WARNING) << "Ignoring incoming connection on medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
channel->GetMedium()) channel->GetMedium())
<< " because client=" << client->GetClientId() << " because client=" << client->GetClientId()
<< " is no longer waiting for incoming connections."; << " is no longer waiting for incoming connections.";
return {Exception::kIo}; return {Exception::kIo};
} }
@@ -1929,11 +1907,10 @@ Exception BasePcpHandler::OnIncomingConnection(
if (!wrapped_frame.ok()) { if (!wrapped_frame.ok()) {
if (wrapped_frame.exception()) { if (wrapped_frame.exception()) {
LOG(ERROR) LOG(ERROR) << "Failed to parse incoming connection request; client="
<< "Failed to parse incoming connection request; client=" << client->GetClientId() << "; device="
<< client->GetClientId() << absl::BytesToHexString(remote_endpoint_info.data())
<< "; device=" << absl::BytesToHexString(remote_endpoint_info.data()) << "with error: " << wrapped_frame.exception();
<< "with error: " << wrapped_frame.exception();
ProcessPreConnectionInitiationFailure( ProcessPreConnectionInitiationFailure(
client, medium, /*endpoint_id=*/"", channel.get(), client, medium, /*endpoint_id=*/"", channel.get(),
/*is_incoming=*/true, start_time, {Status::kError}, /*is_incoming=*/true, start_time, {Status::kError},
@@ -1948,18 +1925,18 @@ Exception BasePcpHandler::OnIncomingConnection(
const ConnectionRequestFrame& connection_request = const ConnectionRequestFrame& connection_request =
frame.v1().connection_request(); frame.v1().connection_request();
LOG(INFO) << "In onIncomingConnection(" LOG(INFO) << "In onIncomingConnection("
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
channel->GetMedium()) channel->GetMedium())
<< ") for client=" << client->GetClientId() << ") for client=" << client->GetClientId()
<< ", read ConnectionRequestFrame from endpoint(id=" << ", read ConnectionRequestFrame from endpoint(id="
<< connection_request.endpoint_id() << ")"; << connection_request.endpoint_id() << ")";
if (client->IsConnectedToEndpoint(connection_request.endpoint_id())) { if (client->IsConnectedToEndpoint(connection_request.endpoint_id())) {
LOG(ERROR) << "Incoming connection on medium " LOG(ERROR) << "Incoming connection on medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
channel->GetMedium()) channel->GetMedium())
<< " was denied because we're " << " was denied because we're "
"already connected to endpoint(id=" "already connected to endpoint(id="
<< connection_request.endpoint_id() << ")."; << connection_request.endpoint_id() << ").";
return {Exception::kIo}; return {Exception::kIo};
} }
@@ -1989,8 +1966,8 @@ Exception BasePcpHandler::OnIncomingConnection(
: NearbyDevice::Type::kConnectionsDevice; : NearbyDevice::Type::kConnectionsDevice;
if (listening_device_type != incoming_type) { if (listening_device_type != incoming_type) {
LOG(WARNING) << "Device requesting a connection is the wrong type." LOG(WARNING) << "Device requesting a connection is the wrong type."
<< "Expected type: " << listening_device_type << "Expected type: " << listening_device_type
<< ", got type: " << incoming_type; << ", got type: " << incoming_type;
return {Exception::kIo}; return {Exception::kIo};
} }
@@ -2019,11 +1996,10 @@ Exception BasePcpHandler::OnIncomingConnection(
connection_options.keep_alive_timeout_millis == 0 || connection_options.keep_alive_timeout_millis == 0 ||
connection_options.keep_alive_interval_millis >= connection_options.keep_alive_interval_millis >=
connection_options.keep_alive_timeout_millis) { connection_options.keep_alive_timeout_millis) {
LOG(WARNING) LOG(WARNING) << "Incoming connection has wrong keep-alive frame interval="
<< "Incoming connection has wrong keep-alive frame interval=" << connection_options.keep_alive_interval_millis
<< connection_options.keep_alive_interval_millis << ", timeout=" << connection_options.keep_alive_timeout_millis
<< ", timeout=" << connection_options.keep_alive_timeout_millis << " values; correct them as default.",
<< " values; correct them as default.",
connection_options.keep_alive_interval_millis = connection_options.keep_alive_interval_millis =
FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis; FeatureFlags::GetInstance().GetFlags().keep_alive_interval_millis;
connection_options.keep_alive_timeout_millis = connection_options.keep_alive_timeout_millis =
@@ -2065,13 +2041,13 @@ Exception BasePcpHandler::OnIncomingConnection(
<< medium_metadata.medium_role().support_awdl_subscriber(); << medium_metadata.medium_role().support_awdl_subscriber();
} else { } else {
LOG(INFO) << connection_request.endpoint_id() LOG(INFO) << connection_request.endpoint_id()
<< "'s WIFI information: is_supports_5_ghz=" << "'s WIFI information: is_supports_5_ghz="
<< connection_info.supports_5_ghz << connection_info.supports_5_ghz
<< "; bssid=" << connection_info.bssid << "; bssid=" << connection_info.bssid
<< "; ap_frequency=" << connection_info.ap_frequency << "; ap_frequency=" << connection_info.ap_frequency
<< "Mhz; ip_address in bytes format=" << "Mhz; ip_address in bytes format="
<< absl::BytesToHexString(connection_info.ip_address) << absl::BytesToHexString(connection_info.ip_address)
<< "; has no mediumRole"; << "; has no mediumRole";
} }
// We've successfully connected to the device, and are now about to jump on to // We've successfully connected to the device, and are now about to jump on to
@@ -2113,16 +2089,15 @@ bool BasePcpHandler::BreakTie(ClientProxy* client,
if (it != pending_connections_.end()) { if (it != pending_connections_.end()) {
BasePcpHandler::PendingConnectionInfo& pending_connection_info = it->second; BasePcpHandler::PendingConnectionInfo& pending_connection_info = it->second;
LOG(INFO) LOG(INFO) << "In onIncomingConnection("
<< "In onIncomingConnection(" << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( endpoint_channel->GetMedium())
endpoint_channel->GetMedium()) << ") for client=" << client->GetClientId()
<< ") for client=" << client->GetClientId() << ", found a collision with endpoint " << endpoint_id
<< ", found a collision with endpoint " << endpoint_id << ". We've already sent a connection request to them with nonce "
<< ". We've already sent a connection request to them with nonce " << pending_connection_info.nonce
<< pending_connection_info.nonce << ", but they're also trying to connect to us with nonce "
<< ", but they're also trying to connect to us with nonce " << incoming_nonce;
<< incoming_nonce;
// Break the lowest connection. In the (extremely) rare case of a tie, break // Break the lowest connection. In the (extremely) rare case of a tie, break
// both. // both.
if (pending_connection_info.nonce > incoming_nonce) { if (pending_connection_info.nonce > incoming_nonce) {
@@ -2130,11 +2105,11 @@ bool BasePcpHandler::BreakTie(ClientProxy* client,
endpoint_channel->Close(); endpoint_channel->Close();
LOG(INFO) << "In onIncomingConnection(" LOG(INFO) << "In onIncomingConnection("
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
endpoint_channel->GetMedium()) endpoint_channel->GetMedium())
<< ") for client=" << client->GetClientId() << ") for client=" << client->GetClientId()
<< ", cleaned up the collision with endpoint " << ", cleaned up the collision with endpoint " << endpoint_id
<< endpoint_id << " by closing their channel."; << " by closing their channel.";
return true; return true;
} else if (pending_connection_info.nonce < incoming_nonce) { } else if (pending_connection_info.nonce < incoming_nonce) {
// Aw, we lost. Clean up our connection, and then we'll let their // Aw, we lost. Clean up our connection, and then we'll let their
@@ -2173,11 +2148,10 @@ Status BasePcpHandler::VerifyConnectionRequest(const std::string& endpoint_id,
// If we already have a pending connection, then we shouldn't allow any // If we already have a pending connection, then we shouldn't allow any
// more outgoing connections to this endpoint. // more outgoing connections to this endpoint.
if (pending_connections_.count(endpoint_id)) { if (pending_connections_.count(endpoint_id)) {
LOG(INFO) LOG(INFO) << "In requestConnection(), connection requested with "
<< "In requestConnection(), connection requested with " "endpoint(id="
"endpoint(id=" << endpoint_id
<< endpoint_id << "), but we already have a pending connection with them.";
<< "), but we already have a pending connection with them.";
return {Status::kAlreadyConnectedToEndpoint}; return {Status::kAlreadyConnectedToEndpoint};
} }
@@ -2185,11 +2159,9 @@ Status BasePcpHandler::VerifyConnectionRequest(const std::string& endpoint_id,
// listen to them. // listen to them.
if (client->ShouldEnforceTopologyConstraints() && if (client->ShouldEnforceTopologyConstraints() &&
!CanSendOutgoingConnection(client)) { !CanSendOutgoingConnection(client)) {
LOG(INFO) << "In requestConnection(), client=" LOG(INFO) << "In requestConnection(), client=" << client->GetClientId()
<< client->GetClientId() << " attempted a connection with endpoint(id=" << endpoint_id
<< " attempted a connection with endpoint(id=" << "), but outgoing connections are disallowed";
<< endpoint_id
<< "), but outgoing connections are disallowed";
return {Status::kOutOfOrderApiCall}; return {Status::kOutOfOrderApiCall};
} }
return {Status::kSuccess}; return {Status::kSuccess};
@@ -2313,7 +2285,7 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
auto it = pending_connections_.find(endpoint_id); auto it = pending_connections_.find(endpoint_id);
if (it == pending_connections_.end()) { if (it == pending_connections_.end()) {
LOG(INFO) << "No pending connection to evaluate; endpoint_id=" LOG(INFO) << "No pending connection to evaluate; endpoint_id="
<< endpoint_id; << endpoint_id;
return; return;
} }
@@ -2323,8 +2295,7 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
std::shared_ptr<EndpointChannel> endpint_channel = std::shared_ptr<EndpointChannel> endpint_channel =
channel_manager_->GetChannelForEndpoint(endpoint_id); channel_manager_->GetChannelForEndpoint(endpoint_id);
if (endpint_channel == nullptr) { if (endpint_channel == nullptr) {
LOG(WARNING) << "No endpint channel for endpoint_id=" LOG(WARNING) << "No endpint channel for endpoint_id=" << endpoint_id;
<< endpoint_id;
return; return;
} }
@@ -2332,8 +2303,7 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
Status response_code; Status response_code;
if (is_connection_accepted) { if (is_connection_accepted) {
LOG(INFO) << "Pending connection accepted; endpoint_id=" LOG(INFO) << "Pending connection accepted; endpoint_id=" << endpoint_id;
<< endpoint_id;
response_code = {Status::kSuccess}; response_code = {Status::kSuccess};
// Both sides have accepted, so we can now start talking over encrypted // Both sides have accepted, so we can now start talking over encrypted
@@ -2358,24 +2328,21 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
if (client->IsMultiplexSocketSupported(endpoint_id, if (client->IsMultiplexSocketSupported(endpoint_id,
channel->GetMedium())) { channel->GetMedium())) {
if (!channel->EnableMultiplexSocket()) { if (!channel->EnableMultiplexSocket()) {
LOG(INFO) LOG(INFO) << "MultiplexSocket is not implemented for Medium: "
<< "MultiplexSocket is not implemented for Medium: " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( channel->GetMedium());
channel->GetMedium());
} else { } else {
LOG(INFO) LOG(INFO) << "MultiplexSocket is supported for Medium: "
<< "MultiplexSocket is supported for Medium: " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( channel->GetMedium())
channel->GetMedium()) << " on both sides.";
<< " on both sides.";
} }
} }
} else { } else {
LOG(INFO) << "channel is null"; LOG(INFO) << "channel is null";
} }
} else { } else {
LOG(INFO) << "Pending connection rejected; endpoint_id=" LOG(INFO) << "Pending connection rejected; endpoint_id=" << endpoint_id;
<< endpoint_id;
response_code = {Status::kConnectionRejected}; response_code = {Status::kConnectionRejected};
} }
@@ -2419,8 +2386,7 @@ void BasePcpHandler::EvaluateConnectionResult(ClientProxy* client,
client->OnBandwidthChanged(endpoint_id, medium); client->OnBandwidthChanged(endpoint_id, medium);
LOG(INFO) << "Connection accepted on Medium:" LOG(INFO) << "Connection accepted on Medium:"
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium);
medium);
// Kick off the bandwidth upgrade for incoming connections. // Kick off the bandwidth upgrade for incoming connections.
if (pending_connection_info.is_incoming && client->AutoUpgradeBandwidth()) { if (pending_connection_info.is_incoming && client->AutoUpgradeBandwidth()) {
@@ -2518,7 +2484,7 @@ void BasePcpHandler::LogConnectionAttemptSuccess(
OperationResultCode::DETAIL_SUCCESS; OperationResultCode::DETAIL_SUCCESS;
} else { } else {
LOG(ERROR) << "PendingConnectionInfo channel is null for " LOG(ERROR) << "PendingConnectionInfo channel is null for "
"LogConnectionAttemptSuccess. Bail out."; "LogConnectionAttemptSuccess. Bail out.";
return; return;
} }
@@ -807,10 +807,9 @@ class BasePcpHandlerTest
.endpoint_channel = nullptr, .endpoint_channel = nullptr,
}; };
} else { } else {
LOG(INFO) LOG(INFO) << "Connect with Medium: "
<< "Connect with Medium: " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( endpoint->medium);
endpoint->medium);
return MockPcpHandler::ConnectImplResult{ return MockPcpHandler::ConnectImplResult{
.medium = endpoint->medium, .medium = endpoint->medium,
.status = {Status::kSuccess}, .status = {Status::kSuccess},
@@ -57,8 +57,7 @@ BluetoothBwuHandler::CreateUpgradedEndpointChannel(
upgrade_path_info.bluetooth_credentials(); upgrade_path_info.bluetooth_credentials();
if (!bluetooth_credentials.has_service_name() || if (!bluetooth_credentials.has_service_name() ||
!bluetooth_credentials.has_mac_address()) { !bluetooth_credentials.has_mac_address()) {
LOG(ERROR) LOG(ERROR) << "BluetoothBwuHandler failed to parse UpgradePathInfo.";
<< "BluetoothBwuHandler failed to parse UpgradePathInfo.";
return { return {
Error(OperationResultCode::CONNECTIVITY_BLUETOOTH_INVALID_CREDENTIAL)}; Error(OperationResultCode::CONNECTIVITY_BLUETOOTH_INVALID_CREDENTIAL)};
} }
@@ -67,9 +66,9 @@ BluetoothBwuHandler::CreateUpgradedEndpointChannel(
const std::string& mac_address = bluetooth_credentials.mac_address(); const std::string& mac_address = bluetooth_credentials.mac_address();
VLOG(1) << "BluetoothBwuHandler is attempting to connect to " VLOG(1) << "BluetoothBwuHandler is attempting to connect to "
"available Bluetooth device (" "available Bluetooth device ("
<< service_name << ", " << mac_address << ") for endpoint " << service_name << ", " << mac_address << ") for endpoint "
<< endpoint_id << " and service ID " << service_id; << endpoint_id << " and service ID " << service_id;
BluetoothDevice device = bluetooth_medium_.GetRemoteDevice(mac_address); BluetoothDevice device = bluetooth_medium_.GetRemoteDevice(mac_address);
if (!device.IsValid()) { if (!device.IsValid()) {
@@ -91,19 +90,17 @@ BluetoothBwuHandler::CreateUpgradedEndpointChannel(
return {Error(socket_result.error().operation_result_code().value())}; return {Error(socket_result.error().operation_result_code().value())};
} }
VLOG(1) VLOG(1) << "BluetoothBwuHandler successfully connected to Bluetooth device ("
<< "BluetoothBwuHandler successfully connected to Bluetooth device (" << service_id << ", " << mac_address << ") while upgrading endpoint "
<< service_id << ", " << mac_address << ") while upgrading endpoint " << endpoint_id;
<< endpoint_id;
auto channel = std::make_unique<BluetoothEndpointChannel>( auto channel = std::make_unique<BluetoothEndpointChannel>(
service_id, /*channel_name=*/service_id, socket_result.value()); service_id, /*channel_name=*/service_id, socket_result.value());
if (channel == nullptr) { if (channel == nullptr) {
LOG(ERROR) LOG(ERROR) << "BluetoothBwuHandler failed to create Bluetooth endpoint "
<< "BluetoothBwuHandler failed to create Bluetooth endpoint " "channel to the Bluetooth device ("
"channel to the Bluetooth device (" << service_name << ", " << mac_address << ") for endpoint "
<< service_name << ", " << mac_address << ") for endpoint " << endpoint_id << " and service ID " << service_id;
<< endpoint_id << " and service ID " << service_id;
socket_result.value().Close(); socket_result.value().Close();
return {Error( return {Error(
OperationResultCode::NEARBY_BT_ENDPOINT_CHANNEL_CREATION_FAILURE)}; OperationResultCode::NEARBY_BT_ENDPOINT_CHANNEL_CREATION_FAILURE)};
@@ -119,9 +116,9 @@ ByteArray BluetoothBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
std::string mac_address = bluetooth_medium_.GetMacAddress(); std::string mac_address = bluetooth_medium_.GetMacAddress();
if (mac_address.empty()) { if (mac_address.empty()) {
LOG(ERROR) << "BluetoothBwuHandler couldn't initiate the " LOG(ERROR) << "BluetoothBwuHandler couldn't initiate the "
"BLUETOOTH upgrade for service ID " "BLUETOOTH upgrade for service ID "
<< upgrade_service_id << " and endpoint " << endpoint_id << upgrade_service_id << " and endpoint " << endpoint_id
<< " because MAC address is empty."; << " because MAC address is empty.";
return {}; return {};
} }
@@ -132,10 +129,10 @@ ByteArray BluetoothBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
&BluetoothBwuHandler::OnIncomingBluetoothConnection, this, &BluetoothBwuHandler::OnIncomingBluetoothConnection, this,
client))) { client))) {
LOG(ERROR) << "BluetoothBwuHandler couldn't initiate the " LOG(ERROR) << "BluetoothBwuHandler couldn't initiate the "
"BLUETOOTH upgrade for endpoint " "BLUETOOTH upgrade for endpoint "
<< endpoint_id << endpoint_id
<< " because it failed to start listening for " << " because it failed to start listening for "
"incoming Bluetooth connections."; "incoming Bluetooth connections.";
return {}; return {};
} }
@@ -151,8 +148,7 @@ ByteArray BluetoothBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
void BluetoothBwuHandler::HandleRevertInitiatorStateForService( void BluetoothBwuHandler::HandleRevertInitiatorStateForService(
const std::string& upgrade_service_id) { const std::string& upgrade_service_id) {
bluetooth_medium_.StopAcceptingConnections(upgrade_service_id); bluetooth_medium_.StopAcceptingConnections(upgrade_service_id);
LOG(INFO) LOG(INFO) << "BluetoothBwuHandler successfully reverted all Bluetooth state.";
<< "BluetoothBwuHandler successfully reverted all Bluetooth state.";
} }
// Accept Connection Callback. // Accept Connection Callback.
@@ -17,8 +17,8 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "absl/time/time.h" #include "absl/time/time.h"
#include "connections/implementation/bwu_handler.h"
#include "connections/implementation/bluetooth_bwu_handler.h" #include "connections/implementation/bluetooth_bwu_handler.h"
#include "connections/implementation/bwu_handler.h"
#include "connections/implementation/client_proxy.h" #include "connections/implementation/client_proxy.h"
#include "connections/implementation/endpoint_channel.h" #include "connections/implementation/endpoint_channel.h"
#include "connections/implementation/mediums/mediums.h" #include "connections/implementation/mediums/mediums.h"
+173 -195
View File
@@ -233,9 +233,9 @@ void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
RunOnBwuManagerThread("bwu-init", [this, client, endpoint_id, RunOnBwuManagerThread("bwu-init", [this, client, endpoint_id,
proposed_medium]() { proposed_medium]() {
LOG(INFO) << "InitiateBwuForEndpoint for endpoint " << endpoint_id LOG(INFO) << "InitiateBwuForEndpoint for endpoint " << endpoint_id
<< " with medium " << " with medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
proposed_medium); proposed_medium);
if (channel_manager_->isWifiLanConnected() && if (channel_manager_->isWifiLanConnected() &&
(proposed_medium == Medium::WIFI_HOTSPOT)) { (proposed_medium == Medium::WIFI_HOTSPOT)) {
@@ -282,10 +282,10 @@ void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
// to Bluetooth. // to Bluetooth.
if (proposed_medium == channel_medium) { if (proposed_medium == channel_medium) {
LOG(INFO) << "BwuManager ignoring the upgrade for endpoint " LOG(INFO) << "BwuManager ignoring the upgrade for endpoint "
<< endpoint_id << endpoint_id
<< " because it is already connected over medium " << " because it is already connected over medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
proposed_medium); proposed_medium);
return; return;
} }
@@ -329,13 +329,12 @@ void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
CONNECTIVITY_GENERIC_WRITING_CHANNEL_IO_ERROR); CONNECTIVITY_GENERIC_WRITING_CHANNEL_IO_ERROR);
return; return;
} }
LOG(INFO) LOG(INFO) << "BwuManager successfully wrote the "
<< "BwuManager successfully wrote the " "BANDWIDTH_UPGRADE_NEGOTIATION.UPGRADE_PATH_REQUEST "
"BANDWIDTH_UPGRADE_NEGOTIATION.UPGRADE_PATH_REQUEST " "OfflineFrame while upgrading endpoint "
"OfflineFrame while upgrading endpoint " << endpoint_id << " to medium "
<< endpoint_id << " to medium " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name( proposed_medium);
proposed_medium);
return; return;
} }
} }
@@ -347,12 +346,12 @@ void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
// Because we grab the endpointChannel first thing, it is possible the // Because we grab the endpointChannel first thing, it is possible the
// endpointChannel is stale by the time we attempt to write over it. // endpointChannel is stale by the time we attempt to write over it.
if (bytes.Empty()) { if (bytes.Empty()) {
LOG(ERROR) LOG(ERROR) << "BwuManager couldn't complete the upgrade for endpoint "
<< "BwuManager couldn't complete the upgrade for endpoint " << endpoint_id << " to medium "
<< endpoint_id << " to medium " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name(proposed_medium) proposed_medium)
<< " because it failed to initialize the " << " because it failed to initialize the "
"BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame."; "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame.";
UpgradePathInfo info; UpgradePathInfo info;
info.set_medium(parser::MediumToUpgradePathInfoMedium(proposed_medium)); info.set_medium(parser::MediumToUpgradePathInfoMedium(proposed_medium));
@@ -368,12 +367,12 @@ void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
return; return;
} }
if (!channel->Write(bytes).Ok()) { if (!channel->Write(bytes).Ok()) {
LOG(ERROR) LOG(ERROR) << "BwuManager couldn't complete the upgrade for endpoint "
<< "BwuManager couldn't complete the upgrade for endpoint " << endpoint_id << " to medium "
<< endpoint_id << " to medium " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name(proposed_medium) proposed_medium)
<< " because it failed to write the " << " because it failed to write the "
"BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame."; "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame.";
UpgradePathInfo info; UpgradePathInfo info;
info.set_medium(parser::MediumToUpgradePathInfoMedium(proposed_medium)); info.set_medium(parser::MediumToUpgradePathInfoMedium(proposed_medium));
@@ -389,12 +388,12 @@ void BwuManager::InitiateBwuForEndpoint(ClientProxy* client,
return; return;
} }
LOG(INFO) LOG(INFO) << "BwuManager successfully wrote the "
<< "BwuManager successfully wrote the " "BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame while "
"BWU_NEGOTIATION.UPGRADE_PATH_AVAILABLE OfflineFrame while " "upgrading endpoint "
"upgrading endpoint " << endpoint_id << " to medium "
<< endpoint_id << " to medium " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name(proposed_medium); proposed_medium);
in_progress_upgrades_.emplace(endpoint_id, client); in_progress_upgrades_.emplace(endpoint_id, client);
}); });
} }
@@ -408,11 +407,10 @@ void BwuManager::OnIncomingFrame(OfflineFrame& frame,
auto bwu_frame = frame.v1().bandwidth_upgrade_negotiation(); auto bwu_frame = frame.v1().bandwidth_upgrade_negotiation();
LOG(INFO) << "OnIncomingFrame: bwu_frame=" LOG(INFO) << "OnIncomingFrame: bwu_frame="
<< BandwidthUpgradeNegotiationFrame::EventType_Name( << BandwidthUpgradeNegotiationFrame::EventType_Name(
bwu_frame.event_type()) bwu_frame.event_type())
<< ", endpoint_id=" << endpoint_id << ", medium=" << ", endpoint_id=" << endpoint_id << ", medium="
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium);
medium);
if (FeatureFlags::GetInstance().GetFlags().enable_async_bandwidth_upgrade) { if (FeatureFlags::GetInstance().GetFlags().enable_async_bandwidth_upgrade) {
RunOnBwuManagerThread( RunOnBwuManagerThread(
"bwu-on-incoming-frame", [this, client, endpoint_id, bwu_frame]() { "bwu-on-incoming-frame", [this, client, endpoint_id, bwu_frame]() {
@@ -434,9 +432,9 @@ void BwuManager::OnEndpointDisconnect(ClientProxy* client,
const std::string& endpoint_id, const std::string& endpoint_id,
CountDownLatch barrier, CountDownLatch barrier,
DisconnectionReason reason) { DisconnectionReason reason) {
LOG(INFO) LOG(INFO) << "BwuManager has processed endpoint disconnection for endpoint "
<< "BwuManager has processed endpoint disconnection for endpoint " << endpoint_id << " with reason "
<< endpoint_id << " with reason " << DisconnectionReason_Name(reason); << DisconnectionReason_Name(reason);
RunOnBwuManagerThread("bwu-on-endpoint-disconnect", [this, client, service_id, RunOnBwuManagerThread("bwu-on-endpoint-disconnect", [this, client, service_id,
endpoint_id, endpoint_id,
barrier]() mutable { barrier]() mutable {
@@ -476,9 +474,8 @@ void BwuManager::RevertBwuMediumForEndpoint(const std::string& service_id,
// approach and revert the handler for _all_ endpoints. // approach and revert the handler for _all_ endpoints.
if (!FeatureFlags::GetInstance().GetFlags().support_multiple_bwu_mediums) { if (!FeatureFlags::GetInstance().GetFlags().support_multiple_bwu_mediums) {
LOG(INFO) << "Reverting medium " LOG(INFO) << "Reverting medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium)
medium) << " for all endpoints for service " << service_id;
<< " for all endpoints for service " << service_id;
medium_ = Medium::UNKNOWN_MEDIUM; medium_ = Medium::UNKNOWN_MEDIUM;
BwuHandler* handler = GetHandlerForMedium(medium); BwuHandler* handler = GetHandlerForMedium(medium);
if (!handler) return; if (!handler) return;
@@ -488,16 +485,15 @@ void BwuManager::RevertBwuMediumForEndpoint(const std::string& service_id,
} }
LOG(INFO) << "Reverting medium " LOG(INFO) << "Reverting medium "
<< location::nearby::proto::connections::Medium_Name(medium) << location::nearby::proto::connections::Medium_Name(medium)
<< " for service ID " << service_id << " and endpoint " << " for service ID " << service_id << " and endpoint "
<< endpoint_id; << endpoint_id;
endpoint_id_to_bwu_medium_.erase(endpoint_id); endpoint_id_to_bwu_medium_.erase(endpoint_id);
BwuHandler* handler = GetHandlerForMedium(medium); BwuHandler* handler = GetHandlerForMedium(medium);
if (!handler) { if (!handler) {
LOG(INFO) << "No BWU handler can be found for " LOG(INFO) << "No BWU handler can be found for "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium);
medium);
return; return;
} }
// If |service_id| isn't of the INITIATOR-upgrade format--for example, if this // If |service_id| isn't of the INITIATOR-upgrade format--for example, if this
@@ -555,8 +551,8 @@ void BwuManager::OnBwuNegotiationFrame(ClientProxy* client,
const BwuNegotiationFrame frame, const BwuNegotiationFrame frame,
const std::string& endpoint_id) { const std::string& endpoint_id) {
LOG(INFO) << "OnBwuNegotiationFrame: processing incoming " LOG(INFO) << "OnBwuNegotiationFrame: processing incoming "
<< BwuNegotiationFrame::EventType_Name(frame.event_type()) << BwuNegotiationFrame::EventType_Name(frame.event_type())
<< " frame for endpoint " << endpoint_id; << " frame for endpoint " << endpoint_id;
if (!client->IsConnectedToEndpoint(endpoint_id)) { if (!client->IsConnectedToEndpoint(endpoint_id)) {
LOG(WARNING) LOG(WARNING)
@@ -625,41 +621,41 @@ void BwuManager::OnIncomingConnection(
} }
VLOG(1) << "BwuManager successfully created new EndpointChannel for " VLOG(1) << "BwuManager successfully created new EndpointChannel for "
"incoming socket"; "incoming socket";
ClientIntroduction introduction; ClientIntroduction introduction;
if (!ReadClientIntroductionFrame(channel, introduction)) { if (!ReadClientIntroductionFrame(channel, introduction)) {
// This was never a fully EstablishedConnection, no need to provide a // This was never a fully EstablishedConnection, no need to provide a
// closure reason. // closure reason.
channel->Close(); channel->Close();
LOG(ERROR) LOG(ERROR) << "BwuManager failed to read "
<< "BwuManager failed to read " "BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame from "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame from " "newly-created EndpointChannel "
"newly-created EndpointChannel " << channel->GetName()
<< channel->GetName() << ", so the EndpointChannel was discarded."; << ", so the EndpointChannel was discarded.";
return; return;
} }
VLOG(1) << "BwuManager successfully received " VLOG(1) << "BwuManager successfully received "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION " "BWU_NEGOTIATION.CLIENT_INTRODUCTION "
"OfflineFrame on EndpointChannel " "OfflineFrame on EndpointChannel "
<< channel->GetName(); << channel->GetName();
if (!WriteClientIntroductionAckFrame(channel)) { if (!WriteClientIntroductionAckFrame(channel)) {
// This was never a fully EstablishedConnection, no need to provide a // This was never a fully EstablishedConnection, no need to provide a
// closure reason. // closure reason.
LOG(ERROR) << "BwuManager failed to write" LOG(ERROR) << "BwuManager failed to write"
"BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK " "BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
"OfflineFrame on EndpointChannel " "OfflineFrame on EndpointChannel "
<< channel->GetName(); << channel->GetName();
channel->Close(); channel->Close();
return; return;
} }
VLOG(1) << "BwuManager successfully wrote " VLOG(1) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK " "BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
"OfflineFrame on EndpointChannel " "OfflineFrame on EndpointChannel "
<< channel->GetName(); << channel->GetName();
const std::string& endpoint_id = introduction.endpoint_id(); const std::string& endpoint_id = introduction.endpoint_id();
ClientProxy* mapped_client; ClientProxy* mapped_client;
@@ -716,9 +712,9 @@ void BwuManager::RunUpgradeProtocol(
ClientProxy* client, const std::string& endpoint_id, ClientProxy* client, const std::string& endpoint_id,
std::unique_ptr<EndpointChannel> new_channel, bool enable_encryption) { std::unique_ptr<EndpointChannel> new_channel, bool enable_encryption) {
LOG(INFO) << "RunUpgradeProtocol new channel @" << new_channel.get() LOG(INFO) << "RunUpgradeProtocol new channel @" << new_channel.get()
<< " name: " << new_channel->GetName() << ", medium: " << " name: " << new_channel->GetName() << ", medium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
new_channel->GetMedium()); new_channel->GetMedium());
// First, register this new EndpointChannel as *the* EndpointChannel to use // First, register this new EndpointChannel as *the* EndpointChannel to use
// for this endpoint here onwards. NOTE: We pause this new EndpointChannel // for this endpoint here onwards. NOTE: We pause this new EndpointChannel
// until we've completely drained the old EndpointChannel to avoid out of // until we've completely drained the old EndpointChannel to avoid out of
@@ -748,11 +744,10 @@ void BwuManager::RunUpgradeProtocol(
// this endpoint by telling the remote device that it will not receive any // this endpoint by telling the remote device that it will not receive any
// more writes over that EndpointChannel. // more writes over that EndpointChannel.
if (!old_channel->Write(parser::ForBwuLastWrite()).Ok()) { if (!old_channel->Write(parser::ForBwuLastWrite()).Ok()) {
LOG(ERROR) LOG(ERROR) << "BwuManager failed to write "
<< "BwuManager failed to write " "BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame to "
"BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL OfflineFrame to " "endpoint "
"endpoint " << endpoint_id << ", short-circuiting the upgrade protocol.";
<< endpoint_id << ", short-circuiting the upgrade protocol.";
client->GetAnalyticsRecorder().OnBandwidthUpgradeError( client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR, endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR,
BandwidthUpgradeErrorStage::LAST_WRITE_TO_PRIOR_CHANNEL, BandwidthUpgradeErrorStage::LAST_WRITE_TO_PRIOR_CHANNEL,
@@ -760,9 +755,9 @@ void BwuManager::RunUpgradeProtocol(
return; return;
} }
VLOG(1) << "BwuManager successfully wrote " VLOG(1) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL " "BWU_NEGOTIATION.LAST_WRITE_TO_PRIOR_CHANNEL "
"OfflineFrame while upgrading endpoint " "OfflineFrame while upgrading endpoint "
<< endpoint_id; << endpoint_id;
// The remainder of this clean shutdown for the previous EndpointChannel will // The remainder of this clean shutdown for the previous EndpointChannel will
// continue when we receive a corresponding // continue when we receive a corresponding
@@ -784,10 +779,10 @@ void BwuManager::ProcessBwuPathAvailableEvent(
const UpgradePathInfo& upgrade_path_info) { const UpgradePathInfo& upgrade_path_info) {
Medium upgrade_medium = Medium upgrade_medium =
parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium()); parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium());
LOG(INFO) << "ProcessBwuPathAvailableEvent for endpoint " LOG(INFO) << "ProcessBwuPathAvailableEvent for endpoint " << endpoint_id
<< endpoint_id << " medium " << " medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
upgrade_medium); upgrade_medium);
if (channel_manager_->isWifiLanConnected() && if (channel_manager_->isWifiLanConnected() &&
((upgrade_medium == Medium::WIFI_HOTSPOT) || ((upgrade_medium == Medium::WIFI_HOTSPOT) ||
@@ -934,29 +929,26 @@ BwuManager::ProcessBwuPathAvailableEventInternal(
Medium medium = Medium medium =
parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium()); parser::UpgradePathInfoMediumToMedium(upgrade_path_info.medium());
if (medium != GetBwuMediumForEndpoint(endpoint_id)) { if (medium != GetBwuMediumForEndpoint(endpoint_id)) {
LOG(ERROR) LOG(ERROR) << "ProcessBwuPathAvailableEventInternal failed for endpoint "
<< "ProcessBwuPathAvailableEventInternal failed for endpoint " << endpoint_id << " medium "
<< endpoint_id << " medium " << location::nearby::proto::connections::Medium_Name(medium)
<< location::nearby::proto::connections::Medium_Name(medium) << ". Upgrade medium not yet set for endpoint.";
<< ". Upgrade medium not yet set for endpoint.";
return {Error(OperationResultCode::NEARBY_UPGRADE_PATH_ON_WRONG_MEDIUM)}; return {Error(OperationResultCode::NEARBY_UPGRADE_PATH_ON_WRONG_MEDIUM)};
} }
BwuHandler* handler = GetHandlerForMedium(medium); BwuHandler* handler = GetHandlerForMedium(medium);
if (!handler) { if (!handler) {
LOG(ERROR) LOG(ERROR) << "ProcessBwuPathAvailableEventInternal failed for endpoint "
<< "ProcessBwuPathAvailableEventInternal failed for endpoint " << endpoint_id << " medium "
<< endpoint_id << " medium " << location::nearby::proto::connections::Medium_Name(medium)
<< location::nearby::proto::connections::Medium_Name(medium) << ". No handler for medium.";
<< ". No handler for medium.";
return {Error(OperationResultCode::NEARBY_UPGRADE_PATH_ON_WRONG_MEDIUM)}; return {Error(OperationResultCode::NEARBY_UPGRADE_PATH_ON_WRONG_MEDIUM)};
} }
LOG(INFO) << "ProcessBwuPathAvailableEventInternal for " LOG(INFO) << "ProcessBwuPathAvailableEventInternal for "
"endpoint " "endpoint "
<< endpoint_id << " medium " << endpoint_id << " medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium);
medium);
// Get service ID from the old channel. Don't keep the old channel's shared // Get service ID from the old channel. Don't keep the old channel's shared
// pointer in scope longer than necessary. // pointer in scope longer than necessary.
@@ -967,11 +959,10 @@ BwuManager::ProcessBwuPathAvailableEventInternal(
std::shared_ptr<EndpointChannel> old_channel = std::shared_ptr<EndpointChannel> old_channel =
channel_manager_->GetChannelForEndpoint(endpoint_id); channel_manager_->GetChannelForEndpoint(endpoint_id);
if (!old_channel) { if (!old_channel) {
LOG(ERROR) LOG(ERROR) << "ProcessBwuPathAvailableEventInternal failed for endpoint "
<< "ProcessBwuPathAvailableEventInternal failed for endpoint " << endpoint_id << " medium "
<< endpoint_id << " medium " << location::nearby::proto::connections::Medium_Name(medium)
<< location::nearby::proto::connections::Medium_Name(medium) << ". Old endpoint channel is missing.";
<< ". Old endpoint channel is missing.";
return { return {
Error(OperationResultCode::NEARBY_GENERIC_OLD_ENDPOINT_CHANNEL_NULL)}; Error(OperationResultCode::NEARBY_GENERIC_OLD_ENDPOINT_CHANNEL_NULL)};
} }
@@ -989,11 +980,10 @@ BwuManager::ProcessBwuPathAvailableEventInternal(
old_medium == Medium::BLE && medium == Medium::WIFI_HOTSPOT) { old_medium == Medium::BLE && medium == Medium::WIFI_HOTSPOT) {
disable_ble_scanning = true; disable_ble_scanning = true;
if (enable_ble_v2) { if (enable_ble_v2) {
LOG(INFO) LOG(INFO) << "For Apple OS, if upgrade from BLE_V2 to WIFI_HOTSPOT, "
<< "For Apple OS, if upgrade from BLE_V2 to WIFI_HOTSPOT, " "we need to pause "
"we need to pause " "BLE_V2 scanning because it can interfere with WIFI "
"BLE_V2 scanning because it can interfere with WIFI " "Hotspot scanning and connection.";
"Hotspot scanning and connection.";
ble_v2_medium_.PauseMediumScanning(); ble_v2_medium_.PauseMediumScanning();
} }
} }
@@ -1016,8 +1006,8 @@ BwuManager::ProcessBwuPathAvailableEventInternal(
if (result.has_error() || !result.has_value()) { if (result.has_error() || !result.has_value()) {
LOG(ERROR) << "BwuManager failed to create an endpoint " LOG(ERROR) << "BwuManager failed to create an endpoint "
"channel to endpoint" "channel to endpoint"
<< endpoint_id << ", aborting upgrade."; << endpoint_id << ", aborting upgrade.";
client->GetAnalyticsRecorder().OnBandwidthUpgradeError( client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR, endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR,
BandwidthUpgradeErrorStage::SOCKET_CREATION, BandwidthUpgradeErrorStage::SOCKET_CREATION,
@@ -1058,9 +1048,9 @@ BwuManager::ProcessBwuPathAvailableEventInternal(
new_channel->Close(); new_channel->Close();
LOG(ERROR) << "BwuManager failed to read " LOG(ERROR) << "BwuManager failed to read "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK " "BWU_NEGOTIATION.CLIENT_INTRODUCTION_ACK "
"OfflineFrame to newly-created EndpointChannel " "OfflineFrame to newly-created EndpointChannel "
<< new_channel->GetName() << ", aborting upgrade."; << new_channel->GetName() << ", aborting upgrade.";
return {Error( return {Error(
OperationResultCode:: OperationResultCode::
NEARBY_GENERIC_READ_CLIENT_INTRODUCTION_ACK_FRAME_TYPE_ERROR)}; NEARBY_GENERIC_READ_CLIENT_INTRODUCTION_ACK_FRAME_TYPE_ERROR)};
@@ -1068,10 +1058,10 @@ BwuManager::ProcessBwuPathAvailableEventInternal(
} }
LOG(INFO) << "BwuManager successfully wrote " LOG(INFO) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame to " "BWU_NEGOTIATION.CLIENT_INTRODUCTION OfflineFrame to "
"newly-created EndpointChannel " "newly-created EndpointChannel "
<< new_channel->GetName() << " while upgrading endpoint " << new_channel->GetName() << " while upgrading endpoint "
<< endpoint_id; << endpoint_id;
// Set the AnalyticsRecorder so that the future closure of this // Set the AnalyticsRecorder so that the future closure of this
// EndpointChannel will be recorded. // EndpointChannel will be recorded.
@@ -1082,10 +1072,10 @@ void BwuManager::RunUpgradeFailedProtocol(
ClientProxy* client, const std::string& endpoint_id, ClientProxy* client, const std::string& endpoint_id,
const UpgradePathInfo& upgrade_path_info) { const UpgradePathInfo& upgrade_path_info) {
LOG(INFO) << "RunUpgradeFailedProtocol for endpoint " << endpoint_id LOG(INFO) << "RunUpgradeFailedProtocol for endpoint " << endpoint_id
<< " medium " << " medium "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
parser::UpgradePathInfoMediumToMedium( parser::UpgradePathInfoMediumToMedium(
upgrade_path_info.medium())); upgrade_path_info.medium()));
// We attempted to connect to the new medium that the remote device has set up // We attempted to connect to the new medium that the remote device has set up
// for us but we failed. We need to let the remote device know so that they // for us but we failed. We need to let the remote device know so that they
// can pick another medium for us to try. // can pick another medium for us to try.
@@ -1108,10 +1098,9 @@ void BwuManager::RunUpgradeFailedProtocol(
if (!channel->Write(parser::ForBwuFailure(upgrade_path_info)).Ok()) { if (!channel->Write(parser::ForBwuFailure(upgrade_path_info)).Ok()) {
channel->Close(DisconnectionReason::IO_ERROR); channel->Close(DisconnectionReason::IO_ERROR);
LOG(ERROR) LOG(ERROR) << "BwuManager failed to write BWU_NEGOTIATION.UPGRADE_FAILURE "
<< "BwuManager failed to write BWU_NEGOTIATION.UPGRADE_FAILURE " "OfflineFrame to endpoint "
"OfflineFrame to endpoint " << endpoint_id << ", short-circuiting the upgrade protocol.";
<< endpoint_id << ", short-circuiting the upgrade protocol.";
client->GetAnalyticsRecorder().OnBandwidthUpgradeError( client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR, endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR,
BandwidthUpgradeErrorStage::NETWORK_AVAILABLE, BandwidthUpgradeErrorStage::NETWORK_AVAILABLE,
@@ -1125,24 +1114,23 @@ void BwuManager::RunUpgradeFailedProtocol(
} }
in_progress_upgrades_.erase(endpoint_id); in_progress_upgrades_.erase(endpoint_id);
LOG(INFO) << "BwuManager has informed endpoint " << endpoint_id LOG(INFO) << "BwuManager has informed endpoint " << endpoint_id
<< " that the bandwidth upgrade failed."; << " that the bandwidth upgrade failed.";
} }
bool BwuManager::ReadClientIntroductionFrame(EndpointChannel* channel, bool BwuManager::ReadClientIntroductionFrame(EndpointChannel* channel,
ClientIntroduction& introduction) { ClientIntroduction& introduction) {
LOG(INFO) << "ReadClientIntroductionFrame with channel name: " LOG(INFO) << "ReadClientIntroductionFrame with channel name: "
<< channel->GetName() << ", medium: " << channel->GetName() << ", medium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
channel->GetMedium()); channel->GetMedium());
CancelableAlarm timeout_alarm( CancelableAlarm timeout_alarm(
"BwuManager::ReadClientIntroductionFrame", "BwuManager::ReadClientIntroductionFrame",
[channel]() { [channel]() {
LOG(ERROR) << "In BwuManager, failed to read the " LOG(ERROR) << "In BwuManager, failed to read the "
"ClientIntroductionFrame after " "ClientIntroductionFrame after "
<< absl::FormatDuration( << absl::FormatDuration(kReadClientIntroductionFrameTimeout)
kReadClientIntroductionFrameTimeout) << ". Timing out and closing EndpointChannel "
<< ". Timing out and closing EndpointChannel " << channel->GetType();
<< channel->GetType();
channel->Close(); channel->Close();
}, },
kReadClientIntroductionFrameTimeout, &alarm_executor_); kReadClientIntroductionFrameTimeout, &alarm_executor_);
@@ -1152,17 +1140,16 @@ bool BwuManager::ReadClientIntroductionFrame(EndpointChannel* channel,
auto transfer(parser::FromBytes(data.result())); auto transfer(parser::FromBytes(data.result()));
if (!transfer.ok()) { if (!transfer.ok()) {
LOG(ERROR) << "In ReadClientIntroductionFrame, attempted to read a " LOG(ERROR) << "In ReadClientIntroductionFrame, attempted to read a "
"ClientIntroductionFrame from EndpointChannel " "ClientIntroductionFrame from EndpointChannel "
<< channel->GetType() << channel->GetType()
<< " but was unable to obtain any OfflineFrame."; << " but was unable to obtain any OfflineFrame.";
return false; return false;
} }
OfflineFrame frame = transfer.result(); OfflineFrame frame = transfer.result();
if (!frame.has_v1() || !frame.v1().has_bandwidth_upgrade_negotiation()) { if (!frame.has_v1() || !frame.v1().has_bandwidth_upgrade_negotiation()) {
LOG(ERROR) LOG(ERROR) << "In ReadClientIntroductionFrame, expected a "
<< "In ReadClientIntroductionFrame, expected a " "BANDWIDTH_UPGRADE_NEGOTIATION v1 OfflineFrame but got a "
"BANDWIDTH_UPGRADE_NEGOTIATION v1 OfflineFrame but got a " << parser::GetFrameType(frame) << " frame instead.";
<< parser::GetFrameType(frame) << " frame instead.";
return false; return false;
} }
if (frame.v1().bandwidth_upgrade_negotiation().event_type() != if (frame.v1().bandwidth_upgrade_negotiation().event_type() !=
@@ -1183,9 +1170,9 @@ bool BwuManager::ReadClientIntroductionFrame(EndpointChannel* channel,
bool BwuManager::ReadClientIntroductionAckFrame(EndpointChannel* channel) { bool BwuManager::ReadClientIntroductionAckFrame(EndpointChannel* channel) {
LOG(INFO) << "ReadClientIntroductionAckFrame with channel name: " LOG(INFO) << "ReadClientIntroductionAckFrame with channel name: "
<< channel->GetName() << ", medium: " << channel->GetName() << ", medium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
channel->GetMedium()); channel->GetMedium());
CancelableAlarm timeout_alarm( CancelableAlarm timeout_alarm(
"BwuManager::ReadClientIntroductionAckFrame", "BwuManager::ReadClientIntroductionAckFrame",
[channel]() { [channel]() {
@@ -1214,9 +1201,9 @@ bool BwuManager::ReadClientIntroductionAckFrame(EndpointChannel* channel) {
bool BwuManager::WriteClientIntroductionAckFrame(EndpointChannel* channel) { bool BwuManager::WriteClientIntroductionAckFrame(EndpointChannel* channel) {
LOG(INFO) << "WriteClientIntroductionAckFrame channel name: " LOG(INFO) << "WriteClientIntroductionAckFrame channel name: "
<< channel->GetName() << ", medium: " << channel->GetName() << ", medium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
channel->GetMedium()); channel->GetMedium());
return channel->Write(parser::ForBwuIntroductionAck()).Ok(); return channel->Write(parser::ForBwuIntroductionAck()).Ok();
} }
@@ -1243,10 +1230,10 @@ void BwuManager::ProcessLastWriteToPriorChannelEvent(
} }
LOG(INFO) << "ProcessLastWriteToPriorChannelEvent: service_id=" LOG(INFO) << "ProcessLastWriteToPriorChannelEvent: service_id="
<< previous_endpoint_channel->GetServiceId() << previous_endpoint_channel->GetServiceId()
<< ", endpoint_id=" << endpoint_id << ", medium=" << ", endpoint_id=" << endpoint_id << ", medium="
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
previous_endpoint_channel->GetMedium()); previous_endpoint_channel->GetMedium());
if (!previous_endpoint_channel->Write(parser::ForBwuSafeToClose()).Ok()) { if (!previous_endpoint_channel->Write(parser::ForBwuSafeToClose()).Ok()) {
previous_endpoint_channel->Close(DisconnectionReason::IO_ERROR); previous_endpoint_channel->Close(DisconnectionReason::IO_ERROR);
@@ -1255,10 +1242,9 @@ void BwuManager::ProcessLastWriteToPriorChannelEvent(
previous_endpoint_channels_.erase(endpoint_id); previous_endpoint_channels_.erase(endpoint_id);
LOG(ERROR) << "BwuManager failed to write " LOG(ERROR) << "BwuManager failed to write "
"BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL " "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
"OfflineFrame to endpoint " "OfflineFrame to endpoint "
<< endpoint_id << endpoint_id << ", short-circuiting the upgrade protocol.";
<< ", short-circuiting the upgrade protocol.";
client->GetAnalyticsRecorder().OnBandwidthUpgradeError( client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR, endpoint_id, BandwidthUpgradeResult::RESULT_IO_ERROR,
BandwidthUpgradeErrorStage::SAFE_TO_CLOSE_PRIOR_CHANNEL, BandwidthUpgradeErrorStage::SAFE_TO_CLOSE_PRIOR_CHANNEL,
@@ -1266,9 +1252,9 @@ void BwuManager::ProcessLastWriteToPriorChannelEvent(
return; return;
} }
VLOG(1) << "BwuManager successfully wrote " VLOG(1) << "BwuManager successfully wrote "
"BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL " "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL "
"OfflineFrame while trying to upgrade endpoint " "OfflineFrame while trying to upgrade endpoint "
<< endpoint_id; << endpoint_id;
// The upgrade protocol's clean shutdown of the prior EndpointChannel will // The upgrade protocol's clean shutdown of the prior EndpointChannel will
// conclude when we receive a corresponding // conclude when we receive a corresponding
@@ -1279,7 +1265,7 @@ void BwuManager::ProcessLastWriteToPriorChannelEvent(
void BwuManager::ProcessSafeToClosePriorChannelEvent( void BwuManager::ProcessSafeToClosePriorChannelEvent(
ClientProxy* client, const std::string& endpoint_id) { ClientProxy* client, const std::string& endpoint_id) {
LOG(INFO) << "ProcessSafeToClosePriorChannelEvent for endpoint " LOG(INFO) << "ProcessSafeToClosePriorChannelEvent for endpoint "
<< endpoint_id; << endpoint_id;
// By this point in the upgrade protocol, there's no more writes happening // By this point in the upgrade protocol, there's no more writes happening
// over the prior EndpointChannel, and the remote device has given us the // over the prior EndpointChannel, and the remote device has given us the
// go-ahead to close this EndpointChannel [1], so we can safely close it // go-ahead to close this EndpointChannel [1], so we can safely close it
@@ -1302,10 +1288,9 @@ void BwuManager::ProcessSafeToClosePriorChannelEvent(
<< endpoint_id << ", can't complete the upgrade protocol."; << endpoint_id << ", can't complete the upgrade protocol.";
return; return;
} }
LOG(INFO) LOG(INFO) << "BwuManager successfully received a "
<< "BwuManager successfully received a " << "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL OfflineFrame while "
<< "BWU_NEGOTIATION.SAFE_TO_CLOSE_PRIOR_CHANNEL OfflineFrame while " << "trying to upgrade endpoint " << endpoint_id;
<< "trying to upgrade endpoint " << endpoint_id;
// Each encrypted message includes the key to decrypt the next message. The // Each encrypted message includes the key to decrypt the next message. The
// disconnect message is optional and may not be received under normal // disconnect message is optional and may not be received under normal
@@ -1313,7 +1298,7 @@ void BwuManager::ProcessSafeToClosePriorChannelEvent(
// serial crypto context does not increment here. // serial crypto context does not increment here.
previous_endpoint_channel->DisableEncryption(); previous_endpoint_channel->DisableEncryption();
LOG(INFO) << "[safe-to-disconnect] Sending " LOG(INFO) << "[safe-to-disconnect] Sending "
"DISCONNECTION frame with request 0, ack 0"; "DISCONNECTION frame with request 0, ack 0";
previous_endpoint_channel->Write( previous_endpoint_channel->Write(
parser::ForDisconnection(/* request_safe_to_disconnect */ false, parser::ForDisconnection(/* request_safe_to_disconnect */ false,
/* ack_safe_to_disconnect */ false)); /* ack_safe_to_disconnect */ false));
@@ -1326,11 +1311,10 @@ void BwuManager::ProcessSafeToClosePriorChannelEvent(
previous_endpoint_channel->Read(); previous_endpoint_channel->Read();
previous_endpoint_channel->Close(DisconnectionReason::UPGRADED); previous_endpoint_channel->Close(DisconnectionReason::UPGRADED);
VLOG(1) VLOG(1) << "BwuManager cleanly shut down prior "
<< "BwuManager cleanly shut down prior " << previous_endpoint_channel->GetType()
<< previous_endpoint_channel->GetType() << " EndpointChannel to conclude upgrade protocol for endpoint "
<< " EndpointChannel to conclude upgrade protocol for endpoint " << endpoint_id;
<< endpoint_id;
// Now the upgrade protocol has completed, record analytics for this new // Now the upgrade protocol has completed, record analytics for this new
// upgraded bandwidth connection... // upgraded bandwidth connection...
@@ -1346,8 +1330,8 @@ void BwuManager::ProcessSafeToClosePriorChannelEvent(
if (!channel) { if (!channel) {
LOG(ERROR) << "BwuManager attempted to resume the current " LOG(ERROR) << "BwuManager attempted to resume the current "
"EndpointChannel with endpoint " "EndpointChannel with endpoint "
<< endpoint_id << ", but none was found."; << endpoint_id << ", but none was found.";
return; return;
} }
@@ -1371,10 +1355,10 @@ void BwuManager::ProcessUpgradeFailureEvent(
const UpgradePathInfo& upgrade_info, BandwidthUpgradeResult result, const UpgradePathInfo& upgrade_info, BandwidthUpgradeResult result,
bool record_analytic, OperationResultCode operation_result_code) { bool record_analytic, OperationResultCode operation_result_code) {
LOG(INFO) << "ProcessUpgradeFailureEvent for endpoint " << endpoint_id LOG(INFO) << "ProcessUpgradeFailureEvent for endpoint " << endpoint_id
<< " from medium: " << " from medium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(
parser::UpgradePathInfoMediumToMedium( parser::UpgradePathInfoMediumToMedium(
upgrade_info.medium())); upgrade_info.medium()));
// The remote device failed to upgrade to the new medium we set up for them. // The remote device failed to upgrade to the new medium we set up for them.
// That's alright! We'll just try the next available medium (if there is one). // That's alright! We'll just try the next available medium (if there is one).
in_progress_upgrades_.erase(endpoint_id); in_progress_upgrades_.erase(endpoint_id);
@@ -1440,9 +1424,8 @@ void BwuManager::TryNextBestUpgradeMediums(
std::vector<Medium> upgrade_mediums) { std::vector<Medium> upgrade_mediums) {
Medium next_medium = ChooseBestUpgradeMedium(endpoint_id, upgrade_mediums); Medium next_medium = ChooseBestUpgradeMedium(endpoint_id, upgrade_mediums);
LOG(INFO) << "Try Next Best Medium for endpoint " << endpoint_id LOG(INFO) << "Try Next Best Medium for endpoint " << endpoint_id
<< " after ChooseBestUpgradeMedium: " << " after ChooseBestUpgradeMedium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(next_medium);
next_medium);
// If current medium is not WiFi and we have not succeeded with upgrading yet, // If current medium is not WiFi and we have not succeeded with upgrading yet,
// retry upgrade. // retry upgrade.
@@ -1451,8 +1434,7 @@ void BwuManager::TryNextBestUpgradeMediums(
Medium current_medium = Medium current_medium =
channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM; channel ? channel->GetMedium() : Medium::UNKNOWN_MEDIUM;
VLOG(1) << "current_medium: " VLOG(1) << "current_medium: "
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(current_medium);
current_medium);
if (current_medium != Medium::WIFI_LAN && if (current_medium != Medium::WIFI_LAN &&
(next_medium == current_medium || next_medium == Medium::UNKNOWN_MEDIUM || (next_medium == current_medium || next_medium == Medium::UNKNOWN_MEDIUM ||
upgrade_mediums.empty())) { upgrade_mediums.empty())) {
@@ -1473,9 +1455,8 @@ void BwuManager::TryNextBestUpgradeMediums(
// Now that we've successfully picked a new upgrade medium to try, // Now that we've successfully picked a new upgrade medium to try,
// re-initiate the bandwidth upgrade. // re-initiate the bandwidth upgrade.
LOG(INFO) << "BwuManager is attempting to upgrade endpoint " LOG(INFO) << "BwuManager is attempting to upgrade endpoint " << endpoint_id
<< endpoint_id << " again with a new bandwidth upgrade medium.";
<< " again with a new bandwidth upgrade medium.";
InitiateBwuForEndpoint(client, endpoint_id, next_medium); InitiateBwuForEndpoint(client, endpoint_id, next_medium);
} }
@@ -1561,11 +1542,11 @@ Medium BwuManager::ChooseBestUpgradeMedium(
location::nearby::proto::connections::Medium_Name(medium), location::nearby::proto::connections::Medium_Name(medium),
"; "); "; ");
} }
LOG(INFO) LOG(INFO) << "Current upgrade medium "
<< "Current upgrade medium " << location::nearby::proto::connections::Medium_Name(
<< location::nearby::proto::connections::Medium_Name(current_medium) current_medium)
<< " is not supported by the remote endpoint (supported mediums: " << " is not supported by the remote endpoint (supported mediums: "
<< mediums_string << ")"; << mediums_string << ")";
} }
return Medium::UNKNOWN_MEDIUM; return Medium::UNKNOWN_MEDIUM;
@@ -1593,8 +1574,7 @@ void BwuManager::RetryUpgradesAfterDelay(ClientProxy* client,
retry_upgrade_alarms_.emplace(endpoint_id, retry_upgrade_alarms_.emplace(endpoint_id,
std::make_pair(std::move(alarm), delay)); std::make_pair(std::move(alarm), delay));
retry_delays_[endpoint_id] = delay; retry_delays_[endpoint_id] = delay;
LOG(INFO) << "Retry bandwidth upgrade after " LOG(INFO) << "Retry bandwidth upgrade after " << absl::FormatDuration(delay);
<< absl::FormatDuration(delay);
} }
void BwuManager::AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint( void BwuManager::AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
@@ -1611,18 +1591,16 @@ void BwuManager::AttemptToRecordBandwidthUpgradeErrorForUnknownEndpoint(
// make for them. // make for them.
client->GetAnalyticsRecorder().OnBandwidthUpgradeError( client->GetAnalyticsRecorder().OnBandwidthUpgradeError(
endpoint_id, result, error_stage, operation_result_code); endpoint_id, result, error_stage, operation_result_code);
LOG(INFO) << "BwuManager got error " LOG(INFO) << "BwuManager got error " << BandwidthUpgradeResult_Name(result)
<< BandwidthUpgradeResult_Name(result) << " at stage " << " at stage " << BandwidthUpgradeErrorStage_Name(error_stage)
<< BandwidthUpgradeErrorStage_Name(error_stage) << " when upgrading endpoint " << endpoint_id;
<< " when upgrading endpoint " << endpoint_id;
} }
// Otherwise, we have no way of knowing which endpoint was trying to connect // Otherwise, we have no way of knowing which endpoint was trying to connect
// to us :( // to us :(
LOG(INFO) << "BwuManager got error " LOG(INFO) << "BwuManager got error " << BandwidthUpgradeResult_Name(result)
<< BandwidthUpgradeResult_Name(result) << " at stage " << " at stage " << BandwidthUpgradeErrorStage_Name(error_stage)
<< BandwidthUpgradeErrorStage_Name(error_stage) << ", but we don't know which endpoint was trying to "
<< ", but we don't know which endpoint was trying to " "connect to us, so skipping analytics for his error.";
"connect to us, so skipping analytics for his error.";
} }
bool BwuManager::NeedToSwitchRole( bool BwuManager::NeedToSwitchRole(
+69 -82
View File
@@ -109,8 +109,8 @@ ClientProxy::ClientProxy(::nearby::analytics::EventLogger* event_logger)
config_package_nearby::nearby_connections_feature:: config_package_nearby::nearby_connections_feature::
kSafeToDisconnectVersion); kSafeToDisconnectVersion);
LOG(INFO) << "[safe-to-disconnect]: Local enabled: " LOG(INFO) << "[safe-to-disconnect]: Local enabled: "
<< supports_safe_to_disconnect_ << supports_safe_to_disconnect_
<< "; Version: " << local_safe_to_disconnect_version_; << "; Version: " << local_safe_to_disconnect_version_;
// Generate a 7 bits dedup value. // Generate a 7 bits dedup value.
absl::BitGen bitgen; absl::BitGen bitgen;
dct_dedup_ = absl::Uniform(bitgen, 0, 1 << 7); dct_dedup_ = absl::Uniform(bitgen, 0, 1 << 7);
@@ -127,21 +127,20 @@ std::string ClientProxy::GetLocalEndpointId() {
return GetEndpointIdForDct().value(); return GetEndpointIdForDct().value();
} else { } else {
if (!local_endpoint_id_.empty()) { if (!local_endpoint_id_.empty()) {
LOG(INFO) << __func__ << ": Reusing cached endpoint id: " LOG(INFO) << __func__
<< local_endpoint_id_; << ": Reusing cached endpoint id: " << local_endpoint_id_;
return local_endpoint_id_; return local_endpoint_id_;
} }
if (external_device_provider_ == nullptr) { if (external_device_provider_ == nullptr) {
local_endpoint_id_ = GenerateLocalEndpointId(); local_endpoint_id_ = GenerateLocalEndpointId();
LOG(INFO) << __func__ << ": Locally generating endpoint id: " LOG(INFO) << __func__
<< local_endpoint_id_; << ": Locally generating endpoint id: " << local_endpoint_id_;
} else { } else {
local_endpoint_id_ = local_endpoint_id_ =
external_device_provider_->GetLocalDevice()->GetEndpointId(); external_device_provider_->GetLocalDevice()->GetEndpointId();
LOG(INFO) LOG(INFO) << __func__
<< __func__ << ": From external device provider, populating endpoint id: "
<< ": From external device provider, populating endpoint id: " << local_endpoint_id_;
<< local_endpoint_id_;
} }
return local_endpoint_id_; return local_endpoint_id_;
} }
@@ -184,10 +183,10 @@ std::string ClientProxy::GenerateLocalEndpointId() {
if (!cached_endpoint_id_.empty()) { if (!cached_endpoint_id_.empty()) {
if (stable_endpoint_id_mode_) { if (stable_endpoint_id_mode_) {
LOG(INFO) << "ClientProxy [Local Endpoint Re-using cached " LOG(INFO) << "ClientProxy [Local Endpoint Re-using cached "
"endpoint id due to in stable endpoint id mode]: " "endpoint id due to in stable endpoint id mode]: "
"client=" "client="
<< GetClientId() << GetClientId()
<< "; cached_endpoint_id_=" << cached_endpoint_id_; << "; cached_endpoint_id_=" << cached_endpoint_id_;
return cached_endpoint_id_; return cached_endpoint_id_;
} }
} }
@@ -195,9 +194,9 @@ std::string ClientProxy::GenerateLocalEndpointId() {
if (high_vis_mode_) { if (high_vis_mode_) {
if (!cached_endpoint_id_.empty()) { if (!cached_endpoint_id_.empty()) {
LOG(INFO) << "ClientProxy [Local Endpoint Re-using cached " LOG(INFO) << "ClientProxy [Local Endpoint Re-using cached "
"endpoint id]: client=" "endpoint id]: client="
<< GetClientId() << GetClientId()
<< "; cached_endpoint_id_=" << cached_endpoint_id_; << "; cached_endpoint_id_=" << cached_endpoint_id_;
return cached_endpoint_id_; return cached_endpoint_id_;
} }
} }
@@ -231,8 +230,7 @@ void ClientProxy::StartedAdvertising(
operation_result_with_mediums, operation_result_with_mediums,
const AdvertisingOptions& advertising_options) { const AdvertisingOptions& advertising_options) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [StartedAdvertising]: client=" LOG(INFO) << "ClientProxy [StartedAdvertising]: client=" << GetClientId();
<< GetClientId();
if (IsFeatureUseStableEndpointIdEnabled()) { if (IsFeatureUseStableEndpointIdEnabled()) {
if (stable_endpoint_id_mode_) { if (stable_endpoint_id_mode_) {
@@ -268,8 +266,7 @@ void ClientProxy::StartedAdvertising(
void ClientProxy::StoppedAdvertising() { void ClientProxy::StoppedAdvertising() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [StoppedAdvertising]: client=" LOG(INFO) << "ClientProxy [StoppedAdvertising]: client=" << GetClientId();
<< GetClientId();
if (IsAdvertising()) { if (IsAdvertising()) {
advertising_info_.Clear(); advertising_info_.Clear();
@@ -436,16 +433,14 @@ void ClientProxy::OnEndpointFound(
location::nearby::proto::connections::Medium medium) { location::nearby::proto::connections::Medium medium) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [Endpoint Found]: [enter] id=" LOG(INFO) << "ClientProxy [Endpoint Found]: [enter] id=" << endpoint_id
<< endpoint_id << "; service=" << service_id << "; service=" << service_id
<< "; info=" << absl::BytesToHexString(endpoint_info.data()) << "; info=" << absl::BytesToHexString(endpoint_info.data())
<< "; medium=" << "; medium="
<< location::nearby::proto::connections::Medium_Name( << location::nearby::proto::connections::Medium_Name(medium);
medium);
if (!IsDiscoveringServiceId(service_id)) { if (!IsDiscoveringServiceId(service_id)) {
LOG(INFO) << "ClientProxy [Endpoint Found]: Ignoring event for id=" LOG(INFO) << "ClientProxy [Endpoint Found]: Ignoring event for id="
<< endpoint_id << endpoint_id << " because this client is not discovering.";
<< " because this client is not discovering.";
return; return;
} }
@@ -467,11 +462,10 @@ void ClientProxy::OnEndpointLost(const std::string& service_id,
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [Endpoint Lost]: [enter] id=" << endpoint_id LOG(INFO) << "ClientProxy [Endpoint Lost]: [enter] id=" << endpoint_id
<< "; service=" << service_id; << "; service=" << service_id;
if (!IsDiscoveringServiceId(service_id)) { if (!IsDiscoveringServiceId(service_id)) {
LOG(INFO) << "ClientProxy [Endpoint Lost]: Ignoring event for id=" LOG(INFO) << "ClientProxy [Endpoint Lost]: Ignoring event for id="
<< endpoint_id << endpoint_id << " because this client is not discovering.";
<< " because this client is not discovering.";
return; return;
} }
@@ -520,10 +514,9 @@ void ClientProxy::OnConnectionInitiated(
// (can not use c++17 features, until chromium does) we unpack manually. // (can not use c++17 features, until chromium does) we unpack manually.
auto& pair_iter = result.first; auto& pair_iter = result.first;
bool inserted = result.second; bool inserted = result.second;
LOG(INFO) LOG(INFO) << "ClientProxy [Connection Initiated]: add Connection: client="
<< "ClientProxy [Connection Initiated]: add Connection: client=" << GetClientId() << "; endpoint_id=" << endpoint_id
<< GetClientId() << "; endpoint_id=" << endpoint_id << "; inserted=" << inserted;
<< "; inserted=" << inserted;
DCHECK(inserted); DCHECK(inserted);
const ConnectionPair& item = pair_iter->second; const ConnectionPair& item = pair_iter->second;
// Notify the client. // Notify the client.
@@ -547,8 +540,8 @@ void ClientProxy::OnConnectionAccepted(const std::string& endpoint_id) {
if (!HasPendingConnectionToEndpoint(endpoint_id)) { if (!HasPendingConnectionToEndpoint(endpoint_id)) {
LOG(INFO) << "ClientProxy [Connection Accepted]: no pending " LOG(INFO) << "ClientProxy [Connection Accepted]: no pending "
"connection; endpoint_id=" "connection; endpoint_id="
<< endpoint_id; << endpoint_id;
return; return;
} }
@@ -567,8 +560,8 @@ void ClientProxy::OnConnectionRejected(const std::string& endpoint_id,
if (!HasPendingConnectionToEndpoint(endpoint_id)) { if (!HasPendingConnectionToEndpoint(endpoint_id)) {
LOG(INFO) << "ClientProxy [Connection Rejected]: no pending " LOG(INFO) << "ClientProxy [Connection Rejected]: no pending "
"connection; endpoint_id=" "connection; endpoint_id="
<< endpoint_id; << endpoint_id;
return; return;
} }
@@ -591,7 +584,7 @@ void ClientProxy::OnBandwidthChanged(const std::string& endpoint_id,
item->first.connection_listener.bandwidth_changed_cb(endpoint_id, item->first.connection_listener.bandwidth_changed_cb(endpoint_id,
new_medium); new_medium);
LOG(INFO) << "ClientProxy [reporting onBandwidthChanged]: client=" LOG(INFO) << "ClientProxy [reporting onBandwidthChanged]: client="
<< GetClientId() << "; endpoint_id=" << endpoint_id; << GetClientId() << "; endpoint_id=" << endpoint_id;
} }
} }
@@ -1040,9 +1033,9 @@ void ClientProxy::OnPayload(const std::string& endpoint_id, Payload payload) {
LookupConnection(endpoint_id); LookupConnection(endpoint_id);
if (item != nullptr) { if (item != nullptr) {
LOG(INFO) << "ClientProxy [reporting onPayloadReceived]: client=" LOG(INFO) << "ClientProxy [reporting onPayloadReceived]: client="
<< GetClientId() << "; endpoint_id=" << endpoint_id << GetClientId() << "; endpoint_id=" << endpoint_id
<< " ; payload {id:" << payload.GetId() << " ; payload {id:" << payload.GetId()
<< ", type:" << payload.GetType() << "}"; << ", type:" << payload.GetType() << "}";
item->second.payload_cb(endpoint_id, std::move(payload)); item->second.payload_cb(endpoint_id, std::move(payload));
} }
} }
@@ -1072,15 +1065,14 @@ void ClientProxy::OnPayloadProgress(const std::string& endpoint_id,
if (info.status == PayloadProgressInfo::Status::kInProgress) { if (info.status == PayloadProgressInfo::Status::kInProgress) {
VLOG(1) << "ClientProxy [reporting onPayloadProgress]: client=" VLOG(1) << "ClientProxy [reporting onPayloadProgress]: client="
<< GetClientId() << "; endpoint_id=" << endpoint_id << GetClientId() << "; endpoint_id=" << endpoint_id
<< "; payload_id=" << info.payload_id << "; payload_id=" << info.payload_id
<< ", payload_status=" << ToString(info.status); << ", payload_status=" << ToString(info.status);
} else { } else {
LOG(INFO) LOG(INFO) << "ClientProxy [reporting onPayloadProgress]: client="
<< "ClientProxy [reporting onPayloadProgress]: client=" << GetClientId() << "; endpoint_id=" << endpoint_id
<< GetClientId() << "; endpoint_id=" << endpoint_id << "; payload_id=" << info.payload_id
<< "; payload_id=" << info.payload_id << ", payload_status=" << ToString(info.status);
<< ", payload_status=" << ToString(info.status);
} }
} }
} }
@@ -1142,15 +1134,14 @@ v3::ConnectionListeningOptions ClientProxy::GetListeningOptions() const {
void ClientProxy::EnterHighVisibilityMode() { void ClientProxy::EnterHighVisibilityMode() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [EnterHighVisibilityMode]: client=" LOG(INFO) << "ClientProxy [EnterHighVisibilityMode]: client="
<< GetClientId(); << GetClientId();
high_vis_mode_ = true; high_vis_mode_ = true;
} }
void ClientProxy::ExitHighVisibilityMode() { void ClientProxy::ExitHighVisibilityMode() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [ExitHighVisibilityMode]: client=" LOG(INFO) << "ClientProxy [ExitHighVisibilityMode]: client=" << GetClientId();
<< GetClientId();
high_vis_mode_ = false; high_vis_mode_ = false;
ScheduleClearCachedEndpointIdAlarm(); ScheduleClearCachedEndpointIdAlarm();
@@ -1159,7 +1150,7 @@ void ClientProxy::ExitHighVisibilityMode() {
void ClientProxy::EnterStableEndpointIdMode() { void ClientProxy::EnterStableEndpointIdMode() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [EnterStableEndpointIdMode]: client=" LOG(INFO) << "ClientProxy [EnterStableEndpointIdMode]: client="
<< GetClientId(); << GetClientId();
stable_endpoint_id_mode_ = true; stable_endpoint_id_mode_ = true;
} }
@@ -1167,7 +1158,7 @@ void ClientProxy::EnterStableEndpointIdMode() {
void ClientProxy::ExitStableEndpointIdMode() { void ClientProxy::ExitStableEndpointIdMode() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "ClientProxy [ExitStableEndpointIdMode]: client=" LOG(INFO) << "ClientProxy [ExitStableEndpointIdMode]: client="
<< GetClientId(); << GetClientId();
stable_endpoint_id_mode_ = false; stable_endpoint_id_mode_ = false;
ScheduleClearCachedEndpointIdAlarm(); ScheduleClearCachedEndpointIdAlarm();
@@ -1178,38 +1169,34 @@ void ClientProxy::ScheduleClearCachedEndpointIdAlarm() {
if (cached_endpoint_id_.empty()) { if (cached_endpoint_id_.empty()) {
VLOG(1) << "ClientProxy [There is no cached local high power " VLOG(1) << "ClientProxy [There is no cached local high power "
"advertising endpoint Id]: client=" "advertising endpoint Id]: client="
<< GetClientId(); << GetClientId();
return; return;
} }
if (IsFeatureUseStableEndpointIdEnabled() && HasOngoingConnection()) { if (IsFeatureUseStableEndpointIdEnabled() && HasOngoingConnection()) {
VLOG(1) << "ClientProxy [Handle clearing cached endpoint ID " VLOG(1) << "ClientProxy [Handle clearing cached endpoint ID "
"during disconnection]: client=" "during disconnection]: client="
<< GetClientId(); << GetClientId();
return; return;
} }
// Schedule to clear cache high visibility mode advertisement endpoint id in // Schedule to clear cache high visibility mode advertisement endpoint id in
// 30s. // 30s.
LOG(INFO) << "ClientProxy [High Visibility Mode Adv, Schedule to " LOG(INFO) << "ClientProxy [High Visibility Mode Adv, Schedule to "
"Clear Cache EndpointId]: client=" "Clear Cache EndpointId]: client="
<< GetClientId() << GetClientId() << "; cached_endpoint_id_=" << cached_endpoint_id_;
<< "; cached_endpoint_id_=" << cached_endpoint_id_; cached_endpoint_id_alarm_ = std::make_unique<CancelableAlarm>(
cached_endpoint_id_alarm_ = "clear_high_power_endpoint_id_cache",
std::make_unique<CancelableAlarm>( [this]() {
"clear_high_power_endpoint_id_cache", MutexLock lock(&mutex_);
[this]() { LOG(INFO) << "ClientProxy [Cleared cached local high power advertising "
MutexLock lock(&mutex_); "endpoint Id.]: client="
LOG(INFO) << GetClientId()
<< "ClientProxy [Cleared cached local high power advertising " << "; cached_endpoint_id_=" << cached_endpoint_id_;
"endpoint Id.]: client=" cached_endpoint_id_.clear();
<< GetClientId() },
<< "; cached_endpoint_id_=" << cached_endpoint_id_; kHighPowerAdvertisementEndpointIdCacheTimeout, &single_thread_executor_);
cached_endpoint_id_.clear();
},
kHighPowerAdvertisementEndpointIdCacheTimeout,
&single_thread_executor_);
} }
void ClientProxy::CancelClearCachedEndpointIdAlarm() { void ClientProxy::CancelClearCachedEndpointIdAlarm() {
@@ -1250,7 +1237,7 @@ std::int32_t ClientProxy::GetLocalMultiplexSocketBitmask() const {
? kWifiLanMultiplexEnabled ? kWifiLanMultiplexEnabled
: 0); : 0);
LOG(INFO) << "ClientProxy [GetLocalMultiplexSocketBitmask]: " LOG(INFO) << "ClientProxy [GetLocalMultiplexSocketBitmask]: "
<< multiplex_bitmask; << multiplex_bitmask;
return multiplex_bitmask; return multiplex_bitmask;
} }
return 0; return 0;
@@ -1263,7 +1250,7 @@ void ClientProxy::SetRemoteMultiplexSocketBitmask(
item->first.remote_multiplex_socket_bitmask = item->first.remote_multiplex_socket_bitmask =
remote_multiplex_socket_bitmask; remote_multiplex_socket_bitmask;
LOG(INFO) << "ClientProxy [SetRemoteMultiplexSocketBitmask]: " LOG(INFO) << "ClientProxy [SetRemoteMultiplexSocketBitmask]: "
<< remote_multiplex_socket_bitmask; << remote_multiplex_socket_bitmask;
} }
} }
@@ -1272,7 +1259,7 @@ bool ClientProxy::IsLocalMultiplexSocketSupported(Medium medium) {
switch (medium) { switch (medium) {
case Medium::BLUETOOTH: case Medium::BLUETOOTH:
LOG(INFO) << "ClientProxy [IsLocalMultiplexSocketSupported]: " LOG(INFO) << "ClientProxy [IsLocalMultiplexSocketSupported]: "
<< (bitmask & kBtMultiplexEnabled); << (bitmask & kBtMultiplexEnabled);
return (bitmask & kBtMultiplexEnabled) != 0; return (bitmask & kBtMultiplexEnabled) != 0;
case Medium::WIFI_LAN: case Medium::WIFI_LAN:
return (bitmask & kWifiLanMultiplexEnabled) != 0; return (bitmask & kWifiLanMultiplexEnabled) != 0;
@@ -1315,7 +1302,7 @@ void ClientProxy::SetWebRtcNonCellular(bool webrtc_non_cellular) {
std::string allow_webrtc_cellular_str = std::string allow_webrtc_cellular_str =
webrtc_non_cellular ? "disallow" : "allow"; webrtc_non_cellular ? "disallow" : "allow";
LOG(INFO) << "ClientProxy: client=" << GetClientId() LOG(INFO) << "ClientProxy: client=" << GetClientId()
<< allow_webrtc_cellular_str << " to use mobile data.", << allow_webrtc_cellular_str << " to use mobile data.",
webrtc_non_cellular_ = webrtc_non_cellular; webrtc_non_cellular_ = webrtc_non_cellular;
} }
@@ -44,8 +44,8 @@ std::string ConnectionsAuthenticationTransport::ReadMessage() const {
return response.result().string_data(); return response.result().string_data();
} }
LOG(WARNING) << "ConnectionsAuthenticationTransport: read failed " LOG(WARNING) << "ConnectionsAuthenticationTransport: read failed "
"with exception/result: " "with exception/result: "
<< response.exception(); << response.exception();
return ""; return "";
} }
+23 -32
View File
@@ -73,10 +73,9 @@ bool HandleEncryptionSuccess(const std::string& endpoint_id,
void CancelableAlarmRunnable(ClientProxy* client, void CancelableAlarmRunnable(ClientProxy* client,
const std::string& endpoint_id, const std::string& endpoint_id,
EndpointChannel* endpoint_channel) { EndpointChannel* endpoint_channel) {
LOG(INFO) << "Timing out encryption for client " LOG(INFO) << "Timing out encryption for client " << client->GetClientId()
<< client->GetClientId() << " to endpoint_id=" << endpoint_id << " after "
<< " to endpoint_id=" << endpoint_id << " after " << absl::FormatDuration(kTimeout);
<< absl::FormatDuration(kTimeout);
endpoint_channel->Close(); endpoint_channel->Close();
} }
@@ -126,9 +125,8 @@ class ServerRunnable final {
return; return;
} }
LOG(INFO) LOG(INFO) << "In StartServer(), read UKEY2 Message 1 from endpoint(id="
<< "In StartServer(), read UKEY2 Message 1 from endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
// Message 2 (Server Init) // Message 2 (Server Init)
std::unique_ptr<std::string> server_init = std::unique_ptr<std::string> server_init =
@@ -149,9 +147,8 @@ class ServerRunnable final {
return; return;
} }
LOG(INFO) LOG(INFO) << "In StartServer(), wrote UKEY2 Message 2 to endpoint(id="
<< "In StartServer(), wrote UKEY2 Message 2 to endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
// Message 3 (Client Finish) // Message 3 (Client Finish)
ExceptionOr<ByteArray> client_finish = channel_->Read(); ExceptionOr<ByteArray> client_finish = channel_->Read();
@@ -175,9 +172,8 @@ class ServerRunnable final {
return; return;
} }
LOG(INFO) LOG(INFO) << "In StartServer(), read UKEY2 Message 3 from endpoint(id="
<< "In StartServer(), read UKEY2 Message 3 from endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
timeout_alarm.Cancel(); timeout_alarm.Cancel();
@@ -191,7 +187,7 @@ class ServerRunnable final {
private: private:
void LogException() const { void LogException() const {
LOG(ERROR) << "In StartServer(), UKEY2 failed with endpoint(id=" LOG(ERROR) << "In StartServer(), UKEY2 failed with endpoint(id="
<< endpoint_id_ << ")."; << endpoint_id_ << ").";
} }
void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) { void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) {
@@ -204,10 +200,9 @@ class ServerRunnable final {
Exception write_exception = Exception write_exception =
channel_->Write(ByteArray(*parse_result.alert_to_send)); channel_->Write(ByteArray(*parse_result.alert_to_send));
if (!write_exception.Ok()) { if (!write_exception.Ok()) {
LOG(WARNING) LOG(WARNING) << "In StartServer(), client " << client_->GetClientId()
<< "In StartServer(), client " << client_->GetClientId() << " failed to pass the alert error message to endpoint(id="
<< " failed to pass the alert error message to endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
} }
} }
@@ -263,9 +258,8 @@ class ClientRunnable final {
return; return;
} }
LOG(INFO) LOG(INFO) << "In StartClient(), wrote UKEY2 Message 1 to endpoint(id="
<< "In StartClient(), wrote UKEY2 Message 1 to endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
// Message 2 (Server Init) // Message 2 (Server Init)
ExceptionOr<ByteArray> server_init = channel_->Read(); ExceptionOr<ByteArray> server_init = channel_->Read();
@@ -289,9 +283,8 @@ class ClientRunnable final {
return; return;
} }
LOG(INFO) LOG(INFO) << "In StartClient(), read UKEY2 Message 2 from endpoint(id="
<< "In StartClient(), read UKEY2 Message 2 from endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
// Message 3 (Client Finish) // Message 3 (Client Finish)
std::unique_ptr<std::string> client_finish = std::unique_ptr<std::string> client_finish =
@@ -312,9 +305,8 @@ class ClientRunnable final {
return; return;
} }
LOG(INFO) LOG(INFO) << "In StartClient(), wrote UKEY2 Message 3 to endpoint(id="
<< "In StartClient(), wrote UKEY2 Message 3 to endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
timeout_alarm.Cancel(); timeout_alarm.Cancel();
@@ -328,7 +320,7 @@ class ClientRunnable final {
private: private:
void LogException() const { void LogException() const {
LOG(ERROR) << "In StartClient(), UKEY2 failed with endpoint(id=" LOG(ERROR) << "In StartClient(), UKEY2 failed with endpoint(id="
<< endpoint_id_ << ")."; << endpoint_id_ << ").";
} }
void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) { void HandleHandshakeOrIoException(CancelableAlarm* timeout_alarm) {
@@ -341,10 +333,9 @@ class ClientRunnable final {
Exception write_exception = Exception write_exception =
channel_->Write(ByteArray(*parse_result.alert_to_send)); channel_->Write(ByteArray(*parse_result.alert_to_send));
if (!write_exception.Ok()) { if (!write_exception.Ok()) {
LOG(WARNING) LOG(WARNING) << "In StartClient(), client " << client_->GetClientId()
<< "In StartClient(), client " << client_->GetClientId() << " failed to pass the alert error message to endpoint(id="
<< " failed to pass the alert error message to endpoint(id=" << endpoint_id_ << ").";
<< endpoint_id_ << ").";
} }
} }
@@ -103,7 +103,7 @@ std::function<void(const ByteArray&)> MakeDataMonitor(absl::string_view label,
*capture += s; *capture += s;
} }
LOG(INFO) << "source='" << label << "'" LOG(INFO) << "source='" << label << "'"
<< "; message='" << s << "'"; << "; message='" << s << "'";
}; };
} }
@@ -243,11 +243,11 @@ TEST(BaseEndpointChannelManagerTest, RegisterChannelEncryptedReadwrite) {
channel_a_raw->Close(DisconnectionReason::LOCAL_DISCONNECTION); channel_a_raw->Close(DisconnectionReason::LOCAL_DISCONNECTION);
channel_b_raw->Close(DisconnectionReason::REMOTE_DISCONNECTION); channel_b_raw->Close(DisconnectionReason::REMOTE_DISCONNECTION);
ecm_a.UnregisterChannelForEndpoint( ecm_a.UnregisterChannelForEndpoint(
std::string(kEndpointId), DisconnectionReason::LOCAL_DISCONNECTION, std::string(kEndpointId), DisconnectionReason::LOCAL_DISCONNECTION,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION); ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
ecm_b.UnregisterChannelForEndpoint( ecm_b.UnregisterChannelForEndpoint(
std::string(kEndpointId), DisconnectionReason::REMOTE_DISCONNECTION, std::string(kEndpointId), DisconnectionReason::REMOTE_DISCONNECTION,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION); ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
} }
TEST(BaseEndpointChannelManagerTest, ReplaceChannelNoEncrypted) { TEST(BaseEndpointChannelManagerTest, ReplaceChannelNoEncrypted) {
@@ -311,11 +311,12 @@ TEST(BaseEndpointChannelManagerTest, ReplaceChannelNoEncrypted) {
channel_a_raw->Close(DisconnectionReason::LOCAL_DISCONNECTION); channel_a_raw->Close(DisconnectionReason::LOCAL_DISCONNECTION);
channel_b_raw->Close(DisconnectionReason::REMOTE_DISCONNECTION); channel_b_raw->Close(DisconnectionReason::REMOTE_DISCONNECTION);
ecm_a.UnregisterChannelForEndpoint( ecm_a.UnregisterChannelForEndpoint(
std::string(kEndpointId), DisconnectionReason::LOCAL_DISCONNECTION, std::string(kEndpointId), DisconnectionReason::LOCAL_DISCONNECTION,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION); ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
ecm_b.UnregisterChannelForEndpoint( ecm_b.UnregisterChannelForEndpoint(
std::string(kEndpointId), DisconnectionReason::REMOTE_DISCONNECTION, std::string(kEndpointId), DisconnectionReason::REMOTE_DISCONNECTION,
ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);} ConnectionsLog::EstablishedConnection::SAFE_DISCONNECTION);
}
} // namespace } // namespace
} // namespace connections } // namespace connections
@@ -206,7 +206,7 @@ ExceptionOr<OfflineFrame> EndpointManager::TryDecryptFrame(
ExceptionOr<ByteArray> decrypted = endpoint_channel->TryDecrypt(data); ExceptionOr<ByteArray> decrypted = endpoint_channel->TryDecrypt(data);
if (decrypted.ok()) { if (decrypted.ok()) {
VLOG(1) << "Message decrypted after " VLOG(1) << "Message decrypted after "
<< SystemClock::ElapsedRealtime() - start_time; << SystemClock::ElapsedRealtime() - start_time;
return parser::FromBytes(decrypted.result()); return parser::FromBytes(decrypted.result());
} }
if (decrypted.exception() == Exception::kExecution) { if (decrypted.exception() == Exception::kExecution) {
@@ -608,7 +608,7 @@ void EndpointManager::RegisterEndpoint(
// and they will happily keep writing to /dev/null. This is why we // and they will happily keep writing to /dev/null. This is why we
// listen for the pong. // listen for the pong.
VLOG(1) << "EndpointManager enabling KeepAlive for endpoint " VLOG(1) << "EndpointManager enabling KeepAlive for endpoint "
<< endpoint_id; << endpoint_id;
endpoint_state.StartEndpointKeepAliveManager( endpoint_state.StartEndpointKeepAliveManager(
[this, client, endpoint_id, keep_alive_interval, [this, client, endpoint_id, keep_alive_interval,
keep_alive_timeout](Mutex* keep_alive_waiter_mutex, keep_alive_timeout](Mutex* keep_alive_waiter_mutex,
@@ -93,8 +93,7 @@ TEST_P(AwdlTest, CanConnect) {
.service_discovered_cb = .service_discovered_cb =
[&discovered_latch, &discovered_service_info]( [&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info, const std::string& service_id) { NsdServiceInfo service_info, const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Discovered service_info=" << &service_info;
<< "Discovered service_info=" << &service_info;
discovered_service_info = service_info; discovered_service_info = service_info;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
@@ -146,8 +145,7 @@ TEST_P(AwdlTest, CanCancelConnect) {
.service_discovered_cb = .service_discovered_cb =
[&discovered_latch, &discovered_service_info]( [&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info, const std::string& service_id) { NsdServiceInfo service_info, const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Discovered service_info=" << &service_info;
<< "Discovered service_info=" << &service_info;
discovered_service_info = service_info; discovered_service_info = service_info;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
+46 -56
View File
@@ -72,17 +72,15 @@ bool Ble::StartAdvertising(const std::string& service_id,
} }
if (advertisement_bytes.size() > kMaxAdvertisementLength) { if (advertisement_bytes.size() > kMaxAdvertisementLength) {
LOG(INFO) LOG(INFO) << "Refusing to start BLE advertising because the advertisement "
<< "Refusing to start BLE advertising because the advertisement " "was too long. Expected at most "
"was too long. Expected at most " << kMaxAdvertisementLength << " bytes but received "
<< kMaxAdvertisementLength << " bytes but received " << advertisement_bytes.size();
<< advertisement_bytes.size();
return false; return false;
} }
if (IsAdvertisingLocked(service_id)) { if (IsAdvertisingLocked(service_id)) {
LOG(INFO) LOG(INFO) << "Failed to BLE advertise because we're already advertising.";
<< "Failed to BLE advertise because we're already advertising.";
return false; return false;
} }
@@ -98,10 +96,10 @@ bool Ble::StartAdvertising(const std::string& service_id,
} }
LOG(INFO) << "Turning on BLE advertising (advertisement size=" LOG(INFO) << "Turning on BLE advertising (advertisement size="
<< advertisement_bytes.size() << ")" << advertisement_bytes.size() << ")"
<< ", service id=" << service_id << ", service id=" << service_id
<< ", fast advertisement service uuid=" << ", fast advertisement service uuid="
<< absl::BytesToHexString(fast_advertisement_service_uuid); << absl::BytesToHexString(fast_advertisement_service_uuid);
// Wrap the connections advertisement to the medium advertisement. // Wrap the connections advertisement to the medium advertisement.
const bool fast_advertisement = !fast_advertisement_service_uuid.empty(); const bool fast_advertisement = !fast_advertisement_service_uuid.empty();
@@ -114,18 +112,17 @@ bool Ble::StartAdvertising(const std::string& service_id,
GenerateDeviceToken()}}; GenerateDeviceToken()}};
if (medium_advertisement_bytes.Empty()) { if (medium_advertisement_bytes.Empty()) {
LOG(INFO) << "Failed to BLE advertise because we could not " LOG(INFO) << "Failed to BLE advertise because we could not "
"create a medium advertisement."; "create a medium advertisement.";
return false; return false;
} }
if (!medium_.StartAdvertising(service_id, medium_advertisement_bytes, if (!medium_.StartAdvertising(service_id, medium_advertisement_bytes,
fast_advertisement_service_uuid)) { fast_advertisement_service_uuid)) {
LOG(ERROR) LOG(ERROR) << "Failed to turn on BLE advertising with advertisement bytes="
<< "Failed to turn on BLE advertising with advertisement bytes=" << absl::BytesToHexString(advertisement_bytes.data())
<< absl::BytesToHexString(advertisement_bytes.data()) << ", size=" << advertisement_bytes.size()
<< ", size=" << advertisement_bytes.size() << ", fast advertisement service uuid="
<< ", fast advertisement service uuid=" << fast_advertisement_service_uuid;
<< fast_advertisement_service_uuid;
return false; return false;
} }
@@ -141,8 +138,7 @@ bool Ble::StopAdvertising(const std::string& service_id) {
return false; return false;
} }
LOG(INFO) << "Turned off BLE advertising with service id=" LOG(INFO) << "Turned off BLE advertising with service id=" << service_id;
<< service_id;
bool ret = medium_.StopAdvertising(service_id); bool ret = medium_.StopAdvertising(service_id);
// Reset our bundle of advertising state to mark that we're no longer // Reset our bundle of advertising state to mark that we're no longer
// advertising. // advertising.
@@ -154,7 +150,7 @@ bool Ble::StartLegacyAdvertising(
const std::string& input_service_id, const std::string& local_endpoint_id, const std::string& input_service_id, const std::string& local_endpoint_id,
const std::string& fast_advertisement_service_uuid) { const std::string& fast_advertisement_service_uuid) {
LOG(INFO) << "StartLegacyAdvertising: " << input_service_id LOG(INFO) << "StartLegacyAdvertising: " << input_service_id
<< ", local_endpoint_id: " << local_endpoint_id; << ", local_endpoint_id: " << local_endpoint_id;
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
std::string service_id = input_service_id + "-Legacy"; std::string service_id = input_service_id + "-Legacy";
@@ -166,13 +162,12 @@ bool Ble::StartLegacyAdvertising(
if (!radio_.IsEnabled()) { if (!radio_.IsEnabled()) {
LOG(INFO) << "Can't start BLE legacy advertising because Bluetooth " LOG(INFO) << "Can't start BLE legacy advertising because Bluetooth "
"was never turned on"; "was never turned on";
return false; return false;
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) LOG(INFO) << "Can't turn on BLE legacy advertising. BLE is not available.";
<< "Can't turn on BLE legacy advertising. BLE is not available.";
return false; return false;
} }
// TODO(hais) improve working dummy set to feed proper hash value. // TODO(hais) improve working dummy set to feed proper hash value.
@@ -182,20 +177,19 @@ bool Ble::StartLegacyAdvertising(
ByteArray encoded_bytes{encoded_legacy_char_array}; ByteArray encoded_bytes{encoded_legacy_char_array};
LOG(INFO) << "Turning on BLE advertising (advertisement size=" LOG(INFO) << "Turning on BLE advertising (advertisement size="
<< encoded_bytes.size() << encoded_bytes.size()
<< "): " << absl::BytesToHexString(encoded_bytes.data()) << "): " << absl::BytesToHexString(encoded_bytes.data())
<< ", service id=" << service_id << ", service id=" << service_id
<< ", fast advertisement service uuid=" << ", fast advertisement service uuid="
<< fast_advertisement_service_uuid; << fast_advertisement_service_uuid;
if (!medium_.StartAdvertising(service_id, encoded_bytes, if (!medium_.StartAdvertising(service_id, encoded_bytes,
fast_advertisement_service_uuid)) { fast_advertisement_service_uuid)) {
LOG(ERROR) LOG(ERROR) << "Failed to turn on BLE advertising with advertisement bytes="
<< "Failed to turn on BLE advertising with advertisement bytes=" << absl::BytesToHexString(encoded_bytes.data())
<< absl::BytesToHexString(encoded_bytes.data()) << ", size=" << encoded_bytes.size()
<< ", size=" << encoded_bytes.size() << ", fast advertisement service uuid="
<< ", fast advertisement service uuid=" << fast_advertisement_service_uuid;
<< fast_advertisement_service_uuid;
return false; return false;
} }
@@ -209,13 +203,12 @@ bool Ble::StopLegacyAdvertising(const std::string& input_service_id) {
std::string service_id = input_service_id + "-Legacy"; std::string service_id = input_service_id + "-Legacy";
if (!IsAdvertisingLocked(service_id)) { if (!IsAdvertisingLocked(service_id)) {
LOG(INFO) LOG(INFO) << "Can't turn off BLE legacy advertising; it is already off";
<< "Can't turn off BLE legacy advertising; it is already off";
return false; return false;
} }
LOG(INFO) << "Turned off BLE legacy advertising with service id=" LOG(INFO) << "Turned off BLE legacy advertising with service id="
<< service_id; << service_id;
bool ret = medium_.StopAdvertising(service_id); bool ret = medium_.StopAdvertising(service_id);
// Reset our bundle of advertising state to mark that we're no longer // Reset our bundle of advertising state to mark that we're no longer
// advertising. // advertising.
@@ -241,14 +234,13 @@ bool Ble::StartScanning(const std::string& service_id,
discovered_peripheral_callback_ = std::move(callback); discovered_peripheral_callback_ = std::move(callback);
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) LOG(INFO) << "Refusing to start BLE scanning with empty service id.";
<< "Refusing to start BLE scanning with empty service id.";
return false; return false;
} }
if (IsScanningLocked(service_id)) { if (IsScanningLocked(service_id)) {
LOG(INFO) << "Refusing to start scan of BLE peripherals because " LOG(INFO) << "Refusing to start scan of BLE peripherals because "
"another scanning is already in-progress."; "another scanning is already in-progress.";
return false; return false;
} }
@@ -259,8 +251,7 @@ bool Ble::StartScanning(const std::string& service_id,
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) LOG(INFO) << "Can't scan BLE peripherals because BLE isn't available.";
<< "Can't scan BLE peripherals because BLE isn't available.";
return false; return false;
} }
@@ -275,7 +266,7 @@ bool Ble::StartScanning(const std::string& service_id,
// Don't bother trying to parse zero byte advertisements. // Don't bother trying to parse zero byte advertisements.
if (medium_advertisement_bytes.size() == 0) { if (medium_advertisement_bytes.size() == 0) {
LOG(INFO) << "Skipping zero byte advertisement " LOG(INFO) << "Skipping zero byte advertisement "
<< "with service_id: " << service_id; << "with service_id: " << service_id;
return; return;
} }
// Unwrap connection BleAdvertisement from medium // Unwrap connection BleAdvertisement from medium
@@ -308,7 +299,7 @@ bool Ble::StopScanning(const std::string& service_id) {
if (!IsScanningLocked(service_id)) { if (!IsScanningLocked(service_id)) {
LOG(INFO) << "Can't turn off BLE scanning because we never " LOG(INFO) << "Can't turn off BLE scanning because we never "
"started scanning."; "started scanning.";
return false; return false;
} }
@@ -346,20 +337,20 @@ bool Ble::StartAcceptingConnections(const std::string& service_id,
} }
if (!radio_.IsEnabled()) { if (!radio_.IsEnabled()) {
LOG(INFO) << "Can't start accepting BLE connections for " LOG(INFO) << "Can't start accepting BLE connections for " << service_id
<< service_id << " because Bluetooth isn't enabled."; << " because Bluetooth isn't enabled.";
return false; return false;
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) << "Can't start accepting BLE connections for " LOG(INFO) << "Can't start accepting BLE connections for " << service_id
<< service_id << " because BLE isn't available."; << " because BLE isn't available.";
return false; return false;
} }
if (!medium_.StartAcceptingConnections(service_id, std::move(callback))) { if (!medium_.StartAcceptingConnections(service_id, std::move(callback))) {
LOG(INFO) << "Failed to accept connections callback for " LOG(INFO) << "Failed to accept connections callback for " << service_id
<< service_id << " ."; << " .";
return false; return false;
} }
@@ -408,13 +399,13 @@ ErrorOr<BleSocket> Ble::Connect(BlePeripheral& peripheral,
if (!radio_.IsEnabled()) { if (!radio_.IsEnabled()) {
LOG(INFO) << "Can't create client BLE socket to " << &peripheral LOG(INFO) << "Can't create client BLE socket to " << &peripheral
<< " because Bluetooth isn't enabled."; << " because Bluetooth isn't enabled.";
return {Error(OperationResultCode::MISCELLEANEOUS_BLE_SYSTEM_SERVICE_NULL)}; return {Error(OperationResultCode::MISCELLEANEOUS_BLE_SYSTEM_SERVICE_NULL)};
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) << "Can't create client BLE socket [service_id=" LOG(INFO) << "Can't create client BLE socket [service_id=" << service_id
<< service_id << "]; BLE isn't available."; << "]; BLE isn't available.";
return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_BLE_NOT_AVAILABLE)}; return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_BLE_NOT_AVAILABLE)};
} }
@@ -426,8 +417,7 @@ ErrorOr<BleSocket> Ble::Connect(BlePeripheral& peripheral,
socket = medium_.Connect(peripheral, service_id, cancellation_flag); socket = medium_.Connect(peripheral, service_id, cancellation_flag);
if (!socket.IsValid()) { if (!socket.IsValid()) {
LOG(INFO) << "Failed to Connect via BLE [service=" << service_id LOG(INFO) << "Failed to Connect via BLE [service=" << service_id << "]";
<< "]";
} }
return socket; return socket;
@@ -88,10 +88,9 @@ TEST_P(BleTest, CanStartAcceptingConnectionsAndConnect) {
BlePeripheral& peripheral, const std::string& service_id, BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes, const ByteArray& advertisement_bytes,
bool fast_advertisement) { bool fast_advertisement) {
LOG(INFO) LOG(INFO) << "Discovered peripheral=" << peripheral.GetName()
<< "Discovered peripheral=" << peripheral.GetName() << ", impl=" << &peripheral.GetImpl()
<< ", impl=" << &peripheral.GetImpl() << ", fast advertisement=" << fast_advertisement;
<< ", fast advertisement=" << fast_advertisement;
atomic_discovered_peripheral.store(peripheral); atomic_discovered_peripheral.store(peripheral);
found_latch.CountDown(); found_latch.CountDown();
}, },
@@ -141,10 +140,9 @@ TEST_P(BleTest, CanCancelConnect) {
BlePeripheral& peripheral, const std::string& service_id, BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes, const ByteArray& advertisement_bytes,
bool fast_advertisement) { bool fast_advertisement) {
LOG(INFO) LOG(INFO) << "Discovered peripheral=" << peripheral.GetName()
<< "Discovered peripheral=" << peripheral.GetName() << ", impl=" << &peripheral.GetImpl()
<< ", impl=" << &peripheral.GetImpl() << ", fast advertisement=" << fast_advertisement;
<< ", fast advertisement=" << fast_advertisement;
atomic_discovered_peripheral.store(peripheral); atomic_discovered_peripheral.store(peripheral);
found_latch.CountDown(); found_latch.CountDown();
}, },
@@ -69,7 +69,7 @@ BleAdvertisementHeader::BleAdvertisementHeader(
advertisement_header_bytes = ble_advertisement_header_bytes; advertisement_header_bytes = ble_advertisement_header_bytes;
} else { } else {
VLOG(1) << "Cannot deserialize BLEAdvertisementHeader. " VLOG(1) << "Cannot deserialize BLEAdvertisementHeader. "
"Invalid advertising data."; "Invalid advertising data.";
return; return;
} }
} else { } else {
@@ -39,8 +39,8 @@ BloomFilter::BloomFilter(std::unique_ptr<BitSet> bit_set,
// If the size is not matched, fall out. // If the size is not matched, fall out.
if (bytes.size() * 8 != bit_set_->Size()) { if (bytes.size() * 8 != bit_set_->Size()) {
LOG(INFO) << "Cannot construct from bytes since the size is not " LOG(INFO) << "Cannot construct from bytes since the size is not "
"matched. bytes.size(x8) = " "matched. bytes.size(x8) = "
<< bytes.size() << ", bit_set.size=" << bit_set_->Size(); << bytes.size() << ", bit_set.size=" << bit_set_->Size();
return; return;
} }
for (size_t byte_index = 0; byte_index < bytes.size(); byte_index++) { for (size_t byte_index = 0; byte_index < bytes.size(); byte_index++) {
@@ -64,9 +64,9 @@ InstantOnLostAdvertisement::CreateFromHashes(
std::string InstantOnLostAdvertisement::ToBytes() const { std::string InstantOnLostAdvertisement::ToBytes() const {
if (hashes_.empty() || hashes_.size() > kMaxHashCount) { if (hashes_.empty() || hashes_.size() > kMaxHashCount) {
LOG(ERROR) << __func__ LOG(ERROR) << __func__
<< ": Failed to convert hashes due to hash " << ": Failed to convert hashes due to hash "
"size is not valid, size = " "size is not valid, size = "
<< hashes_.size(); << hashes_.size();
return ""; return "";
} }
@@ -80,9 +80,9 @@ std::string InstantOnLostAdvertisement::ToBytes() const {
for (const auto& hash : hashes_) { for (const auto& hash : hashes_) {
if (hash.length() != kAdvertisementHashLength) { if (hash.length() != kAdvertisementHashLength) {
LOG(ERROR) << __func__ LOG(ERROR) << __func__
<< ": Failed to convert hashes to advertisement due " << ": Failed to convert hashes to advertisement due "
"to invalid hash : " "to invalid hash : "
<< absl::BytesToHexString(hash); << absl::BytesToHexString(hash);
return ""; return "";
} }
absl::StrAppend(&result, hash); absl::StrAppend(&result, hash);
@@ -112,9 +112,8 @@ TEST_P(BleV2Test, CanConnect) {
const ByteArray& advertisement_bytes, const ByteArray& advertisement_bytes,
bool fast_advertisement) { bool fast_advertisement) {
discovered_peripheral = peripheral; discovered_peripheral = peripheral;
LOG(INFO) LOG(INFO) << "Discovered peripheral, fast advertisement="
<< "Discovered peripheral, fast advertisement=" << fast_advertisement;
<< fast_advertisement;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
}); });
@@ -172,9 +171,8 @@ TEST_P(BleV2Test, CanCancelConnect) {
const ByteArray& advertisement_bytes, const ByteArray& advertisement_bytes,
bool fast_advertisement) { bool fast_advertisement) {
discovered_peripheral = peripheral; discovered_peripheral = peripheral;
LOG(INFO) LOG(INFO) << "Discovered peripheral, fast advertisement="
<< "Discovered peripheral, fast advertisement=" << fast_advertisement;
<< fast_advertisement;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
}); });
@@ -269,7 +269,7 @@ TEST_P(BluetoothClassicTest, CanConnect) {
[&latch, &discovered_device](BluetoothDevice& device) { [&latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Discovered device=" << device.GetName() LOG(INFO) << "Discovered device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
latch.CountDown(); latch.CountDown();
}, },
})); }));
@@ -319,7 +319,7 @@ TEST_P(BluetoothClassicTest, CanCancelBeforeConnect) {
.device_discovered_cb = .device_discovered_cb =
[&latch, &discovered_device](BluetoothDevice& device) { [&latch, &discovered_device](BluetoothDevice& device) {
LOG(INFO) << "Discovered device=" << device.GetName() LOG(INFO) << "Discovered device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
discovered_device = device; discovered_device = device;
latch.CountDown(); latch.CountDown();
}, },
@@ -387,7 +387,7 @@ TEST_P(BluetoothClassicTest, CanCancelDuringConnect) {
[&latch, &discovered_device](BluetoothDevice& device) { [&latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Discovered device=" << device.GetName() LOG(INFO) << "Discovered device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
latch.CountDown(); latch.CountDown();
}, },
})); }));
@@ -453,7 +453,7 @@ TEST_P(BluetoothClassicTest, CanCancelDuringConnect_MultipleEndpoints) {
[&latch, &discovered_device](BluetoothDevice& device) { [&latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Discovered device=" << device.GetName() LOG(INFO) << "Discovered device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
latch.CountDown(); latch.CountDown();
}, },
})); }));
@@ -599,21 +599,21 @@ TEST_F(BluetoothClassicTest, CanDiscoverDeviceChanges) {
[&discovered_latch, &discovered_device](BluetoothDevice& device) { [&discovered_latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Discovered device=" << device.GetName() LOG(INFO) << "Discovered device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
.device_name_changed_cb = .device_name_changed_cb =
[&rename_latch, &discovered_device](BluetoothDevice& device) { [&rename_latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Rename device=" << device.GetName() LOG(INFO) << "Rename device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
rename_latch.CountDown(); rename_latch.CountDown();
}, },
.device_lost_cb = .device_lost_cb =
[&lost_latch, &discovered_device](BluetoothDevice& device) { [&lost_latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Lost device=" << device.GetName() LOG(INFO) << "Lost device=" << device.GetName()
<< ", impl=" << &device.GetImpl(); << ", impl=" << &device.GetImpl();
lost_latch.CountDown(); lost_latch.CountDown();
}, },
})); }));
@@ -645,7 +645,7 @@ TEST_F(BluetoothClassicTest, CanStartAcceptingConnections) {
[&latch, &discovered_device](BluetoothDevice& device) { [&latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device; discovered_device = device;
LOG(INFO) << "Discovered device=" << device.GetName() LOG(INFO) << "Discovered device=" << device.GetName()
<< ",impl=" << &device.GetImpl(); << ",impl=" << &device.GetImpl();
latch.CountDown(); latch.CountDown();
}, },
})); }));
@@ -23,15 +23,14 @@
#include "internal/platform/exception.h" #include "internal/platform/exception.h"
#include "internal/platform/logging.h" #include "internal/platform/logging.h"
namespace nearby { namespace nearby {
namespace connections { namespace connections {
namespace mediums { namespace mediums {
namespace multiplex { namespace multiplex {
using ::location::nearby::mediums::MultiplexFrame;
using ::location::nearby::mediums::MultiplexControlFrame;
using ::location::nearby::mediums::ConnectionResponseFrame; using ::location::nearby::mediums::ConnectionResponseFrame;
using ::location::nearby::mediums::MultiplexControlFrame;
using ::location::nearby::mediums::MultiplexFrame;
ByteArray GenerateServiceIdHash(const std::string& service_id) { ByteArray GenerateServiceIdHash(const std::string& service_id) {
return Utils::Sha256Hash(service_id, kServiceIdHashLength); return Utils::Sha256Hash(service_id, kServiceIdHashLength);
@@ -115,8 +114,7 @@ ByteArray ForDisconnection(const std::string& service_id,
header->set_service_id_hash_salt(service_id_hash_salt); header->set_service_id_hash_salt(service_id_hash_salt);
auto* control_frame = frame.mutable_control_frame(); auto* control_frame = frame.mutable_control_frame();
control_frame->set_control_frame_type( control_frame->set_control_frame_type(MultiplexControlFrame::DISCONNECTION);
MultiplexControlFrame::DISCONNECTION);
return ToBytes(std::move(frame)); return ToBytes(std::move(frame));
} }
@@ -140,7 +138,7 @@ ByteArray ForData(const std::string& service_id,
return ToBytes(std::move(frame)); return ToBytes(std::move(frame));
} }
ExceptionOr<MultiplexFrame> FromBytes(const ByteArray& multiplex_frame_bytes){ ExceptionOr<MultiplexFrame> FromBytes(const ByteArray& multiplex_frame_bytes) {
MultiplexFrame frame; MultiplexFrame frame;
if (frame.ParseFromString(std::string(multiplex_frame_bytes))) { if (frame.ParseFromString(std::string(multiplex_frame_bytes))) {
@@ -173,24 +171,24 @@ bool IsValid(const MultiplexFrame& frame) {
} }
bool IsValidControlFrame(const MultiplexFrame& frame) { bool IsValidControlFrame(const MultiplexFrame& frame) {
if (!frame.has_control_frame()) { if (!frame.has_control_frame()) {
return false;
}
switch (frame.control_frame().control_frame_type()) {
case MultiplexControlFrame::CONNECTION_REQUEST:
case MultiplexControlFrame::CONNECTION_RESPONSE:
case MultiplexControlFrame::DISCONNECTION:
if (frame.header().salted_service_id_hash().size() ==
kServiceIdHashLength) {
return true;
}
break;
default:
break;
}
return false; return false;
}
switch (frame.control_frame().control_frame_type()) {
case MultiplexControlFrame::CONNECTION_REQUEST:
case MultiplexControlFrame::CONNECTION_RESPONSE:
case MultiplexControlFrame::DISCONNECTION:
if (frame.header().salted_service_id_hash().size() ==
kServiceIdHashLength) {
return true;
}
break;
default:
break;
}
return false;
} }
bool IsValidDataFrame(const MultiplexFrame& frame) { bool IsValidDataFrame(const MultiplexFrame& frame) {
@@ -204,8 +202,8 @@ bool IsMultiplexFrame(const ByteArray& data) {
return false; return false;
} else { } else {
LOG(INFO) << "Checked data is a multiplex frame. Is Control ? " LOG(INFO) << "Checked data is a multiplex frame. Is Control ? "
<< frame.result().has_control_frame() << ", is data ? " << frame.result().has_control_frame() << ", is data ? "
<< frame.result().has_data_frame(); << frame.result().has_data_frame();
return true; return true;
} }
} }
@@ -63,16 +63,14 @@ Exception MultiplexOutputStream::WaitForResult(const std::string& method_name,
.mediums_frame_write_timeout_millis); .mediums_frame_write_timeout_millis);
if (!result.ok()) { if (!result.ok()) {
LOG(INFO) << "Future:[" << method_name LOG(INFO) << "Future:[" << method_name
<< "] completed with exception:" << result.exception(); << "] completed with exception:" << result.exception();
return {Exception::kFailed}; return {Exception::kFailed};
} }
if (result.result()) { if (result.result()) {
LOG(INFO) << "Future:[" << method_name LOG(INFO) << "Future:[" << method_name << "] completed with success.";
<< "] completed with success.";
return {Exception::kSuccess}; return {Exception::kSuccess};
} }
LOG(INFO) << "Future:[" << method_name LOG(INFO) << "Future:[" << method_name << "] completed with failure.";
<< "] completed with failure.";
return {Exception::kFailed}; return {Exception::kFailed};
} }
@@ -111,8 +109,8 @@ bool MultiplexOutputStream::WriteConnectionResponseFrame(
bool MultiplexOutputStream::Close(const std::string& service_id) { bool MultiplexOutputStream::Close(const std::string& service_id) {
auto item = virtual_output_streams_.find(service_id); auto item = virtual_output_streams_.find(service_id);
if (item == virtual_output_streams_.end()) { if (item == virtual_output_streams_.end()) {
LOG(INFO) << "Don't need to close VirtualOutputStream(" LOG(INFO) << "Don't need to close VirtualOutputStream(" << service_id
<< service_id << ") because it's already gone."; << ") because it's already gone.";
return false; return false;
} }
@@ -230,8 +228,7 @@ void MultiplexOutputStream::MultiplexWriter::StartWriting() {
LOG(INFO) << "Waiting for data_queue_ has data."; LOG(INFO) << "Waiting for data_queue_ has data.";
Exception wait_succeeded = is_writing_cond_.Wait(); Exception wait_succeeded = is_writing_cond_.Wait();
if (!wait_succeeded.Ok()) { if (!wait_succeeded.Ok()) {
LOG(WARNING) LOG(WARNING) << "Failure waiting to wait: " << wait_succeeded.value;
<< "Failure waiting to wait: " << wait_succeeded.value;
return; return;
} }
} }
@@ -306,9 +303,8 @@ MultiplexOutputStream::VirtualOutputStream::VirtualOutputStream(
Exception MultiplexOutputStream::VirtualOutputStream::Write( Exception MultiplexOutputStream::VirtualOutputStream::Write(
const ByteArray& data) { const ByteArray& data) {
if (is_closed_.Get()) { if (is_closed_.Get()) {
LOG(WARNING) LOG(WARNING) << "Failed to write data because the VirtualOutputStream for "
<< "Failed to write data because the VirtualOutputStream for " << service_id_ << " closed";
<< service_id_ << " closed";
return {Exception::kIo}; return {Exception::kIo};
} }
if (multiplex_output_stream_.is_enabled_.Get()) { if (multiplex_output_stream_.is_enabled_.Get()) {
@@ -327,7 +323,7 @@ Exception MultiplexOutputStream::VirtualOutputStream::Write(
if ((service_id_hash_salt_ == kFakeSalt) && !should_pass_salt) { if ((service_id_hash_salt_ == kFakeSalt) && !should_pass_salt) {
should_pass_salt = true; should_pass_salt = true;
LOG(INFO) << "service_idHashSalt is still a fake one and " LOG(INFO) << "service_idHashSalt is still a fake one and "
"not changed yet; continue to pass salt."; "not changed yet; continue to pass salt.";
} }
} }
ByteArray data_frame = ByteArray data_frame =
@@ -75,8 +75,8 @@ class MultiplexOutputStreamTest : public ::testing::Test {
}; };
TEST_F(MultiplexOutputStreamTest, SendConnectionRequestFrame) { TEST_F(MultiplexOutputStreamTest, SendConnectionRequestFrame) {
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
EXPECT_TRUE(multiplex_output_stream_->WriteConnectionRequestFrame( EXPECT_TRUE(multiplex_output_stream_->WriteConnectionRequestFrame(
std::string(kServiceId_1), std::string(kNoSalt))); std::string(kServiceId_1), std::string(kNoSalt)));
@@ -94,8 +94,8 @@ TEST_F(MultiplexOutputStreamTest, SendConnectionRequestFrame) {
TEST_F(MultiplexOutputStreamTest, SendConnectionRequestFrameDisabled) { TEST_F(MultiplexOutputStreamTest, SendConnectionRequestFrameDisabled) {
enabled_.Set(false); enabled_.Set(false);
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
EXPECT_FALSE(multiplex_output_stream_->WriteConnectionRequestFrame( EXPECT_FALSE(multiplex_output_stream_->WriteConnectionRequestFrame(
std::string(kServiceId_1), std::string(kNoSalt))); std::string(kServiceId_1), std::string(kNoSalt)));
@@ -103,8 +103,8 @@ TEST_F(MultiplexOutputStreamTest, SendConnectionRequestFrameDisabled) {
} }
TEST_F(MultiplexOutputStreamTest, SendConnectionResponseFrame) { TEST_F(MultiplexOutputStreamTest, SendConnectionResponseFrame) {
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
EXPECT_TRUE(multiplex_output_stream_->WriteConnectionResponseFrame( EXPECT_TRUE(multiplex_output_stream_->WriteConnectionResponseFrame(
GenerateServiceIdHash(std::string(kServiceId_1)), std::string(kNoSalt), GenerateServiceIdHash(std::string(kServiceId_1)), std::string(kNoSalt),
ConnectionResponseFrame::CONNECTION_ACCEPTED)); ConnectionResponseFrame::CONNECTION_ACCEPTED));
@@ -127,8 +127,8 @@ TEST_F(MultiplexOutputStreamTest, SendConnectionResponseFrame) {
TEST_F(MultiplexOutputStreamTest, SendConnectionResponseFrameDisabled) { TEST_F(MultiplexOutputStreamTest, SendConnectionResponseFrameDisabled) {
enabled_.Set(false); enabled_.Set(false);
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
EXPECT_FALSE(multiplex_output_stream_->WriteConnectionResponseFrame( EXPECT_FALSE(multiplex_output_stream_->WriteConnectionResponseFrame(
GenerateServiceIdHash(std::string(kServiceId_1)), std::string(kNoSalt), GenerateServiceIdHash(std::string(kServiceId_1)), std::string(kNoSalt),
ConnectionResponseFrame::CONNECTION_ACCEPTED)); ConnectionResponseFrame::CONNECTION_ACCEPTED));
@@ -137,16 +137,16 @@ TEST_F(MultiplexOutputStreamTest, SendConnectionResponseFrameDisabled) {
} }
TEST_F(MultiplexOutputStreamTest, CloseVirtualStreamFailed) { TEST_F(MultiplexOutputStreamTest, CloseVirtualStreamFailed) {
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
EXPECT_FALSE(multiplex_output_stream_->Close(std::string(kServiceId_1))); EXPECT_FALSE(multiplex_output_stream_->Close(std::string(kServiceId_1)));
multiplex_output_stream_->Shutdown(); multiplex_output_stream_->Shutdown();
} }
TEST_F(MultiplexOutputStreamTest, CloseVirtualStreamSuccess) { TEST_F(MultiplexOutputStreamTest, CloseVirtualStreamSuccess) {
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
EXPECT_FALSE(multiplex_output_stream_->Close(std::string(kServiceId_1))); EXPECT_FALSE(multiplex_output_stream_->Close(std::string(kServiceId_1)));
multiplex_output_stream_->CreateVirtualOutputStream(std::string(kServiceId_1), multiplex_output_stream_->CreateVirtualOutputStream(std::string(kServiceId_1),
@@ -166,8 +166,8 @@ TEST_F(MultiplexOutputStreamTest, CloseVirtualStreamSuccess) {
} }
TEST_F(MultiplexOutputStreamTest, CreateVirtualStream_SendData) { TEST_F(MultiplexOutputStreamTest, CreateVirtualStream_SendData) {
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
auto virtual_output_stream = auto virtual_output_stream =
multiplex_output_stream_->CreateVirtualOutputStream( multiplex_output_stream_->CreateVirtualOutputStream(
@@ -189,8 +189,8 @@ TEST_F(MultiplexOutputStreamTest, CreateVirtualStream_SendData) {
} }
TEST_F(MultiplexOutputStreamTest, CreateTwoVirtualStreams_SendData) { TEST_F(MultiplexOutputStreamTest, CreateTwoVirtualStreams_SendData) {
multiplex_output_stream_ = std::make_unique<MultiplexOutputStream>( multiplex_output_stream_ =
writer_.get(), enabled_); std::make_unique<MultiplexOutputStream>(writer_.get(), enabled_);
auto virtual_output_stream_1 = auto virtual_output_stream_1 =
multiplex_output_stream_->CreateVirtualOutputStreamForFirstVirtualSocket( multiplex_output_stream_->CreateVirtualOutputStreamForFirstVirtualSocket(
@@ -222,14 +222,14 @@ TEST_F(MultiplexOutputStreamTest, CreateTwoVirtualStreams_SendData) {
EXPECT_EQ(frame.frame_type(), MultiplexFrame::DATA_FRAME); EXPECT_EQ(frame.frame_type(), MultiplexFrame::DATA_FRAME);
bool first_frame_is_data_1 = true; bool first_frame_is_data_1 = true;
if (frame.header().salted_service_id_hash() == if (frame.header().salted_service_id_hash() ==
std::string(GenerateServiceIdHashWithSalt(std::string(kServiceId_1), std::string(GenerateServiceIdHashWithSalt(std::string(kServiceId_1),
std::string(kSalt_1)))) { std::string(kSalt_1)))) {
EXPECT_EQ(frame.data_frame().data(), std::string(data_1)); EXPECT_EQ(frame.data_frame().data(), std::string(data_1));
LOG(INFO) << "Read first virtual stream frame first."; LOG(INFO) << "Read first virtual stream frame first.";
} else { } else {
EXPECT_EQ(frame.header().salted_service_id_hash(), EXPECT_EQ(frame.header().salted_service_id_hash(),
std::string(GenerateServiceIdHashWithSalt(std::string(kServiceId_2), std::string(GenerateServiceIdHashWithSalt(
std::string(kSalt_2)))); std::string(kServiceId_2), std::string(kSalt_2))));
EXPECT_EQ(frame.data_frame().data(), std::string(data_2)); EXPECT_EQ(frame.data_frame().data(), std::string(data_2));
first_frame_is_data_1 = false; first_frame_is_data_1 = false;
LOG(INFO) << "Read second virtual stream frame first."; LOG(INFO) << "Read second virtual stream frame first.";
@@ -69,7 +69,7 @@ using ConnectionResponseCode = ConnectionResponseFrame::ConnectionResponseCode;
// AtomicBoolean is trivial destructible, so it is safe to use it as a static // AtomicBoolean is trivial destructible, so it is safe to use it as a static
// variable. // variable.
AtomicBoolean MultiplexSocket::is_shutting_down_{false}; // NOLINT AtomicBoolean MultiplexSocket::is_shutting_down_{false}; // NOLINT
void MultiplexSocket::ListenForIncomingConnection( void MultiplexSocket::ListenForIncomingConnection(
const std::string& service_id, Medium type, const std::string& service_id, Medium type,
@@ -131,14 +131,14 @@ MultiplexSocket* MultiplexSocket::CreateIncomingSocket(
new (&storage_wlan) MultiplexSocket(physical_socket); new (&storage_wlan) MultiplexSocket(physical_socket);
break; break;
default: default:
LOG(ERROR) << __func__ << "Unsupported medium: " LOG(ERROR) << __func__
<< physical_socket->GetMedium(); << "Unsupported medium: " << physical_socket->GetMedium();
multiplex_incoming_socket = nullptr; multiplex_incoming_socket = nullptr;
return multiplex_incoming_socket; return multiplex_incoming_socket;
} }
LOG(INFO) << "CreateIncomingSocket with serviceId=" << service_id LOG(INFO) << "CreateIncomingSocket with serviceId=" << service_id
<< ", serviceIdHashSalt=" << kFakeSalt << " for medium=" << ", serviceIdHashSalt=" << kFakeSalt
<< Medium_Name(physical_socket->GetMedium()); << " for medium=" << Medium_Name(physical_socket->GetMedium());
multiplex_incoming_socket->CreateFirstVirtualSocket(service_id, multiplex_incoming_socket->CreateFirstVirtualSocket(service_id,
(std::string)kFakeSalt); (std::string)kFakeSalt);
@@ -175,14 +175,13 @@ MultiplexSocket* MultiplexSocket::CreateOutgoingSocket(
new (&storage_wlan) MultiplexSocket(physical_socket); new (&storage_wlan) MultiplexSocket(physical_socket);
break; break;
default: default:
LOG(ERROR) << __func__ << "Unsupported medium: " LOG(ERROR) << __func__
<< physical_socket->GetMedium(); << "Unsupported medium: " << physical_socket->GetMedium();
return multiplex_outgoing_socket; return multiplex_outgoing_socket;
} }
LOG(INFO) << "CreateOutgoingSocket with serviceId=" << service_id LOG(INFO) << "CreateOutgoingSocket with serviceId=" << service_id
<< ", serviceIdHashSalt=" << service_id_hash_salt << ", serviceIdHashSalt=" << service_id_hash_salt
<< " for medium=" << " for medium=" << Medium_Name(physical_socket->GetMedium());
<< Medium_Name(physical_socket->GetMedium());
multiplex_outgoing_socket->CreateFirstVirtualSocket(service_id, multiplex_outgoing_socket->CreateFirstVirtualSocket(service_id,
service_id_hash_salt); service_id_hash_salt);
@@ -207,9 +206,8 @@ MediumSocket* MultiplexSocket::CreateFirstVirtualSocket(
std::string salted_service_id_hash_key = std::string salted_service_id_hash_key =
GenerateServiceIdHashKeyWithSalt(service_id, service_id_hash_salt); GenerateServiceIdHashKeyWithSalt(service_id, service_id_hash_salt);
LOG(INFO) << __func__ << " for service_id=" << service_id LOG(INFO) << __func__ << " for service_id=" << service_id
<< ", salt=" << service_id_hash_salt << ", salt=" << service_id_hash_salt
<< ", salted_service_id_hash_key=" << ", salted_service_id_hash_key=" << salted_service_id_hash_key;
<< salted_service_id_hash_key;
MediumSocket* virtual_socket = physical_socket_ptr_->CreateVirtualSocket( MediumSocket* virtual_socket = physical_socket_ptr_->CreateVirtualSocket(
salted_service_id_hash_key, output_stream, medium_, &virtual_sockets_); salted_service_id_hash_key, output_stream, medium_, &virtual_sockets_);
@@ -234,9 +232,8 @@ MediumSocket* MultiplexSocket::CreateVirtualSocket(
GenerateServiceIdHashKeyWithSalt(service_id, service_id_hash_salt); GenerateServiceIdHashKeyWithSalt(service_id, service_id_hash_salt);
LOG(INFO) << __func__ << "service_id=" << service_id LOG(INFO) << __func__ << "service_id=" << service_id
<< ", salt=" << service_id_hash_salt << ", salt=" << service_id_hash_salt
<< ", salted_service_id_hash_key=" << ", salted_service_id_hash_key=" << salted_service_id_hash_key;
<< salted_service_id_hash_key;
MediumSocket* virtual_socket = physical_socket_ptr_->CreateVirtualSocket( MediumSocket* virtual_socket = physical_socket_ptr_->CreateVirtualSocket(
salted_service_id_hash_key, output_stream, medium_, &virtual_sockets_); salted_service_id_hash_key, output_stream, medium_, &virtual_sockets_);
@@ -251,8 +248,8 @@ MediumSocket* MultiplexSocket::CreateVirtualSocket(
MediumSocket* MultiplexSocket::GetVirtualSocket(const std::string& service_id) { MediumSocket* MultiplexSocket::GetVirtualSocket(const std::string& service_id) {
MutexLock lock(&virtual_socket_mutex_); MutexLock lock(&virtual_socket_mutex_);
LOG(INFO) << __func__ << " service_id=" << service_id << ", Salt=" LOG(INFO) << __func__ << " service_id=" << service_id << ", Salt="
<< multiplex_output_stream_.GetServiceIdHashSalt(service_id) << multiplex_output_stream_.GetServiceIdHashSalt(service_id)
<< ", virtual_sockets_.size()=" << virtual_sockets_.size(); << ", virtual_sockets_.size()=" << virtual_sockets_.size();
auto item = virtual_sockets_.find(GenerateServiceIdHashKeyWithSalt( auto item = virtual_sockets_.find(GenerateServiceIdHashKeyWithSalt(
service_id, multiplex_output_stream_.GetServiceIdHashSalt(service_id))); service_id, multiplex_output_stream_.GetServiceIdHashSalt(service_id)));
if (item == virtual_sockets_.end()) { if (item == virtual_sockets_.end()) {
@@ -269,11 +266,10 @@ int MultiplexSocket::GetVirtualSocketCount() {
void MultiplexSocket::ListVirtualSocket() { void MultiplexSocket::ListVirtualSocket() {
LOG(INFO) << __func__ LOG(INFO) << __func__
<< " virtual_sockets_.size()=" << virtual_sockets_.size(); << " virtual_sockets_.size()=" << virtual_sockets_.size();
for (auto& [service_id_hash_key, virtual_socket] : virtual_sockets_) { for (auto& [service_id_hash_key, virtual_socket] : virtual_sockets_) {
LOG(INFO) << __func__ LOG(INFO) << __func__ << " service_id_hash_key=" << service_id_hash_key
<< " service_id_hash_key=" << service_id_hash_key << ", virtual_socket=" << virtual_socket;
<< ", virtual_socket=" << virtual_socket;
} }
} }
@@ -309,8 +305,8 @@ MediumSocket* MultiplexSocket::EstablishVirtualSocket(
.multiplex_socket_connection_response_timeout_millis); .multiplex_socket_connection_response_timeout_millis);
if (!result.ok()) { if (!result.ok()) {
LOG(ERROR) << __func__ LOG(ERROR) << __func__
<< "EstablishVirtualSocket failed with response code=" << "EstablishVirtualSocket failed with response code="
<< result.exception(); << result.exception();
return nullptr; return nullptr;
} }
@@ -318,21 +314,21 @@ MediumSocket* MultiplexSocket::EstablishVirtualSocket(
switch (response_code) { switch (response_code) {
case ConnectionResponseFrame::CONNECTION_ACCEPTED: case ConnectionResponseFrame::CONNECTION_ACCEPTED:
LOG(INFO) << "EstablishVirtualSocket after remote response to" LOG(INFO) << "EstablishVirtualSocket after remote response to"
" accept the connection with service_id=" " accept the connection with service_id="
<< service_id << service_id
<< ", service_id_hash_salt=" << service_id_hash_salt; << ", service_id_hash_salt=" << service_id_hash_salt;
return CreateVirtualSocket(service_id, service_id_hash_salt); return CreateVirtualSocket(service_id, service_id_hash_salt);
case ConnectionResponseFrame::NOT_LISTENING: case ConnectionResponseFrame::NOT_LISTENING:
LOG(ERROR) << "EstablishVirtualSocket failed for service_id=" LOG(ERROR) << "EstablishVirtualSocket failed for service_id="
<< service_id << service_id
<< ", service_id_hash_salt=" << service_id_hash_salt << ", service_id_hash_salt=" << service_id_hash_salt
<< " with response code=NOT_LISTENING"; << " with response code=NOT_LISTENING";
break; break;
default: default:
LOG(ERROR) << "EstablishVirtualSocket failed for service_id=" LOG(ERROR) << "EstablishVirtualSocket failed for service_id="
<< service_id << service_id
<< ", service_id_hash_salt=" << service_id_hash_salt << ", service_id_hash_salt=" << service_id_hash_salt
<< " with response code=UNKNOWN_RESPONSE_CODE"; << " with response code=UNKNOWN_RESPONSE_CODE";
break; break;
} }
return nullptr; return nullptr;
@@ -341,7 +337,7 @@ MediumSocket* MultiplexSocket::EstablishVirtualSocket(
void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) { void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) {
if (is_shutdown_) { if (is_shutdown_) {
LOG(WARNING) << "Stop to start reader thread since socket is " LOG(WARNING) << "Stop to start reader thread since socket is "
"shutdown."; "shutdown.";
return; return;
} }
reader_thread_shutdown_barrier_ = std::make_unique<CountDownLatch>(1); reader_thread_shutdown_barrier_ = std::make_unique<CountDownLatch>(1);
@@ -359,8 +355,8 @@ void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) {
read_int = Base64Utils::ReadInt(physical_reader_); read_int = Base64Utils::ReadInt(physical_reader_);
} }
if (!read_int.ok()) { if (!read_int.ok()) {
LOG(WARNING) LOG(WARNING) << __func__
<< __func__ << "Failed to read. Exception:" << read_int.exception(); << "Failed to read. Exception:" << read_int.exception();
fail = true; fail = true;
} else { } else {
auto length = read_int.result(); auto length = read_int.result();
@@ -371,16 +367,16 @@ void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) {
.connection_max_frame_length) { .connection_max_frame_length) {
// Ignore the failure because not only one client use this // Ignore the failure because not only one client use this
// connection. // connection.
LOG(WARNING) LOG(WARNING) << __func__
<< __func__ << "Failed to read because received a invalid length " << "Failed to read because received a invalid length "
<< length << ", but continue to read."; << length << ", but continue to read.";
continue; continue;
} }
bytes = physical_reader_->ReadExactly(length); bytes = physical_reader_->ReadExactly(length);
if (!bytes.ok()) { if (!bytes.ok()) {
LOG(WARNING) LOG(WARNING) << __func__
<< __func__ << "Read data exception:" << bytes.exception(); << "Read data exception:" << bytes.exception();
fail = true; fail = true;
} }
} }
@@ -402,10 +398,9 @@ void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) {
// the remote, it means that the remote and the local both // the remote, it means that the remote and the local both
// support multiplex as well. So it is safe to just turn on // support multiplex as well. So it is safe to just turn on
// the feature at this point. // the feature at this point.
LOG(INFO) LOG(INFO) << __func__
<< __func__ << " Received a multiplex frame while not enabled, enable "
<< " Received a multiplex frame while not enabled, enable " "multiplex.";
"multiplex.";
Enable(); Enable();
} }
const auto& frame = frame_exc.result(); const auto& frame = frame_exc.result();
@@ -425,9 +420,9 @@ void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) {
frame.data_frame()); frame.data_frame());
break; break;
default: default:
LOG(WARNING) LOG(WARNING) << __func__
<< __func__ << " Received MultiplexFrame with unknown frame type " << " Received MultiplexFrame with unknown frame type "
<< frame.frame_type(); << frame.frame_type();
} }
} }
}); });
@@ -435,8 +430,7 @@ void MultiplexSocket::StartReaderThread(std::int32_t first_frame_len) {
void MultiplexSocket::HandleOfflineFrame(const ByteArray& bytes) { void MultiplexSocket::HandleOfflineFrame(const ByteArray& bytes) {
MutexLock lock(&virtual_socket_mutex_); MutexLock lock(&virtual_socket_mutex_);
LOG(INFO) << __func__ LOG(INFO) << __func__ << " Virtual_socket num:" << virtual_sockets_.size();
<< " Virtual_socket num:" << virtual_sockets_.size();
if (virtual_sockets_.size() == 1) { if (virtual_sockets_.size() == 1) {
auto item = virtual_sockets_.begin(); auto item = virtual_sockets_.begin();
if (item->second == nullptr) { if (item->second == nullptr) {
@@ -461,12 +455,12 @@ void MultiplexSocket::HandleControlFrame(
}); });
break; break;
case MultiplexControlFrame::CONNECTION_RESPONSE: case MultiplexControlFrame::CONNECTION_RESPONSE:
LOG(INFO) LOG(INFO) << __func__ << "Received an CONNECTION_RESPONSE frame."
<< __func__ << "Received an CONNECTION_RESPONSE frame." << " salted_service_id_hash: "
<< " salted_service_id_hash: " << std::string(salted_service_id_hash) << std::string(salted_service_id_hash)
<< ", service_id_hash_salt: " << service_id_hash_salt << ", service_id_hash_salt: " << service_id_hash_salt
<< ", ConnectionResponseCode: " << ", ConnectionResponseCode: "
<< frame.connection_response_frame().connection_response_code(); << frame.connection_response_frame().connection_response_code();
RunOffloadThread("CONNECTION_RESPONSE", [this, salted_service_id_hash, RunOffloadThread("CONNECTION_RESPONSE", [this, salted_service_id_hash,
service_id_hash_salt, service_id_hash_salt,
@@ -482,7 +476,7 @@ void MultiplexSocket::HandleControlFrame(
break; break;
default: default:
LOG(WARNING) << __func__ << "Received an unknown frame type " LOG(WARNING) << __func__ << "Received an unknown frame type "
<< frame.control_frame_type(); << frame.control_frame_type();
break; break;
} }
} }
@@ -492,8 +486,8 @@ void MultiplexSocket::HandleConnectionRequest(
const std::string& service_id_hash_salt) { const std::string& service_id_hash_salt) {
if (!IsEnabled()) { if (!IsEnabled()) {
LOG(WARNING) << "Received a CONNECTION_REQUEST frame on medium " LOG(WARNING) << "Received a CONNECTION_REQUEST frame on medium "
<< Medium_Name(medium_) << Medium_Name(medium_)
<< " but status is disabled, ignore it."; << " but status is disabled, ignore it.";
return; return;
} }
@@ -513,12 +507,12 @@ void MultiplexSocket::HandleConnectionRequest(
if (incoming_connection_callback == nullptr || listening_service_id.empty()) { if (incoming_connection_callback == nullptr || listening_service_id.empty()) {
LOG(INFO) << "There's no client listening for hash salt : " LOG(INFO) << "There's no client listening for hash salt : "
<< service_id_hash_salt << service_id_hash_salt
<< ", hash key : " << salted_service_id_hash_key << ", hash key : " << salted_service_id_hash_key << " on medium "
<< " on medium " << Medium_Name(medium_); << Medium_Name(medium_);
LOG(INFO) << "The size of incomingConnectionCallbacks : " LOG(INFO) << "The size of incomingConnectionCallbacks : "
<< GetIncomingConnectionCallbacks().size(); << GetIncomingConnectionCallbacks().size();
if (!multiplex_output_stream_.WriteConnectionResponseFrame( if (!multiplex_output_stream_.WriteConnectionResponseFrame(
salted_service_id_hash, service_id_hash_salt, salted_service_id_hash, service_id_hash_salt,
ConnectionResponseFrame::NOT_LISTENING)) { ConnectionResponseFrame::NOT_LISTENING)) {
@@ -527,10 +521,9 @@ void MultiplexSocket::HandleConnectionRequest(
return; return;
} }
LOG(INFO) << "Accept new virtual socket request service ID : " LOG(INFO) << "Accept new virtual socket request service ID : "
<< listening_service_id << listening_service_id << ", hash salt : " << service_id_hash_salt
<< ", hash salt : " << service_id_hash_salt << ", hash key : " << salted_service_id_hash_key << " on medium "
<< ", hash key : " << salted_service_id_hash_key << Medium_Name(medium_);
<< " on medium " << Medium_Name(medium_);
if (!multiplex_output_stream_.WriteConnectionResponseFrame( if (!multiplex_output_stream_.WriteConnectionResponseFrame(
salted_service_id_hash, service_id_hash_salt, salted_service_id_hash, service_id_hash_salt,
@@ -539,10 +532,10 @@ void MultiplexSocket::HandleConnectionRequest(
return; return;
} }
VLOG(1) VLOG(1) << "EstablishVirtualSocket after local device accept the connection "
<< "EstablishVirtualSocket after local device accept the connection " "with serviceId="
"with serviceId=" << listening_service_id
<< listening_service_id << ", serviceIdHashSalt=" << service_id_hash_salt; << ", serviceIdHashSalt=" << service_id_hash_salt;
MediumSocket* virtual_socket = MediumSocket* virtual_socket =
CreateVirtualSocket(listening_service_id, service_id_hash_salt); CreateVirtualSocket(listening_service_id, service_id_hash_salt);
(*incoming_connection_callback)(std::move(listening_service_id), (*incoming_connection_callback)(std::move(listening_service_id),
@@ -553,18 +546,16 @@ void MultiplexSocket::HandleConnectionResponse(
const ByteArray& salted_service_id_hash, const ByteArray& salted_service_id_hash,
const std::string& service_id_hash_salt, const std::string& service_id_hash_salt,
const ConnectionResponseFrame& frame) { const ConnectionResponseFrame& frame) {
LOG(INFO) << __func__ << "connection_response_code: " LOG(INFO) << __func__
<< frame.connection_response_code(); << "connection_response_code: " << frame.connection_response_code();
for (auto& [service_id, future] : connection_response_futures_) { for (auto& [service_id, future] : connection_response_futures_) {
if (GenerateServiceIdHashWithSalt(service_id, service_id_hash_salt) == if (GenerateServiceIdHashWithSalt(service_id, service_id_hash_salt) ==
salted_service_id_hash) { salted_service_id_hash) {
if (future != nullptr) { if (future != nullptr) {
future->Set(frame.connection_response_code()); future->Set(frame.connection_response_code());
LOG(INFO) << __func__ LOG(INFO) << __func__ << "Set the future for serviceId=" << service_id
<< "Set the future for serviceId=" << service_id << ", serviceIdHashSalt=" << service_id_hash_salt
<< ", serviceIdHashSalt=" << service_id_hash_salt << " with response code=" << frame.connection_response_code();
<< " with response code="
<< frame.connection_response_code();
return; return;
} }
} }
@@ -639,37 +630,36 @@ void MultiplexSocket::OnVirtualSocketClosed(const std::string& service_id) {
LOG(INFO) << __func__ << " for service_id:" << service_id; LOG(INFO) << __func__ << " for service_id:" << service_id;
CountDownLatch latch(1); CountDownLatch latch(1);
bool shutdown = false; bool shutdown = false;
RunOffloadThread("VirtualSocketClosed", [this, service_id, &latch, RunOffloadThread(
&shutdown]() { "VirtualSocketClosed", [this, service_id, &latch, &shutdown]() {
LOG(INFO) << "Try to close Virtual socket: " << service_id; LOG(INFO) << "Try to close Virtual socket: " << service_id;
MediumSocket* virtual_socket = GetVirtualSocket(service_id); MediumSocket* virtual_socket = GetVirtualSocket(service_id);
{ {
MutexLock lock(&virtual_socket_mutex_); MutexLock lock(&virtual_socket_mutex_);
LOG(INFO) << "virtual_socket:" << virtual_socket; LOG(INFO) << "virtual_socket:" << virtual_socket;
if (virtual_socket != nullptr) { if (virtual_socket != nullptr) {
auto salted_service_id_hash_key = GenerateServiceIdHashKeyWithSalt( auto salted_service_id_hash_key = GenerateServiceIdHashKeyWithSalt(
service_id, service_id,
multiplex_output_stream_.GetServiceIdHashSalt(service_id)); multiplex_output_stream_.GetServiceIdHashSalt(service_id));
multiplex_output_stream_.Close(service_id); multiplex_output_stream_.Close(service_id);
virtual_sockets_.erase(salted_service_id_hash_key); virtual_sockets_.erase(salted_service_id_hash_key);
LOG(INFO) << "Erase Virtual socket with service_id: " LOG(INFO) << "Erase Virtual socket with service_id: " << service_id
<< service_id << ", hash_key: " << salted_service_id_hash_key;
<< ", hash_key: " << salted_service_id_hash_key; ListVirtualSocket();
ListVirtualSocket();
if (virtual_sockets_.empty()) { if (virtual_sockets_.empty()) {
LOG(INFO) << "Close the physical socket because all virtual " LOG(INFO) << "Close the physical socket because all virtual "
"sockets disconnected."; "sockets disconnected.";
is_shutting_down_.Set(true); is_shutting_down_.Set(true);
Shutdown(); Shutdown();
shutdown = true; shutdown = true;
}
} else {
LOG(INFO) << "Virtual socket(" << service_id << ") not found";
}
} }
} else { latch.CountDown();
LOG(INFO) << "Virtual socket(" << service_id << ") not found"; });
}
}
latch.CountDown();
});
if (!latch.Await(absl::Milliseconds(1000)).result()) { if (!latch.Await(absl::Milliseconds(1000)).result()) {
LOG(ERROR) << "Timeout to close virtual socket"; LOG(ERROR) << "Timeout to close virtual socket";
@@ -690,8 +680,8 @@ MediumSocket* MultiplexSocket::ReMapAndGetVirtualSocket(
std::string salted_service_id_hash_key = std::string salted_service_id_hash_key =
GenerateServiceIdHashKey(salted_service_id_hash); GenerateServiceIdHashKey(salted_service_id_hash);
VLOG(1) << "ReMapAndGetVirtualSocket with serviceIdHashSalt=" VLOG(1) << "ReMapAndGetVirtualSocket with serviceIdHashSalt="
<< service_id_hash_salt << service_id_hash_salt
<< ", saltedServiceIdHashKey=" << salted_service_id_hash_key; << ", saltedServiceIdHashKey=" << salted_service_id_hash_key;
{ {
MutexLock lock(&virtual_socket_mutex_); MutexLock lock(&virtual_socket_mutex_);
for (auto& [hash_key, virtual_socket] : virtual_sockets_) { for (auto& [hash_key, virtual_socket] : virtual_sockets_) {
@@ -779,8 +769,7 @@ void MultiplexSocket::ShutdownAll() {
LOG(ERROR) << "Timeout to close virtual socket"; LOG(ERROR) << "Timeout to close virtual socket";
} }
LOG(INFO) LOG(INFO) << "Shutdown single_thread_offloader_ and physical_reader_thread_";
<< "Shutdown single_thread_offloader_ and physical_reader_thread_";
single_thread_offloader_.Shutdown(); single_thread_offloader_.Shutdown();
physical_reader_thread_.Shutdown(); physical_reader_thread_.Shutdown();
LOG(INFO) << __func__ << " end"; LOG(INFO) << __func__ << " end";
@@ -50,9 +50,9 @@ namespace multiplex {
constexpr absl::string_view SERVICE_ID_1 = "serviceId_1"; constexpr absl::string_view SERVICE_ID_1 = "serviceId_1";
constexpr absl::string_view SERVICE_ID_2 = "serviceId_2"; constexpr absl::string_view SERVICE_ID_2 = "serviceId_2";
using location::nearby::mediums::MultiplexFrame;
using location::nearby::mediums::MultiplexControlFrame;
using location::nearby::mediums::ConnectionResponseFrame; using location::nearby::mediums::ConnectionResponseFrame;
using location::nearby::mediums::MultiplexControlFrame;
using location::nearby::mediums::MultiplexFrame;
using location::nearby::proto::connections::Medium; using location::nearby::proto::connections::Medium;
using location::nearby::proto::connections::Medium_Name; using location::nearby::proto::connections::Medium_Name;
@@ -66,8 +66,7 @@ class FakeSocket : public MediumSocket {
pipe_2_ = CreatePipe(); pipe_2_ = CreatePipe();
reader_2_ = std::move(pipe_2_.first); reader_2_ = std::move(pipe_2_.first);
writer_2_ = std::move(pipe_2_.second); writer_2_ = std::move(pipe_2_.second);
LOG(WARNING) << "Physical Socket Medium:" LOG(WARNING) << "Physical Socket Medium:" << Medium_Name(GetMedium());
<< Medium_Name(GetMedium());
}; };
~FakeSocket() override = default; ~FakeSocket() override = default;
@@ -117,22 +116,21 @@ class FakeSocket : public MediumSocket {
auto virtual_socket = std::make_shared<FakeSocket>(medium, outputstream); auto virtual_socket = std::make_shared<FakeSocket>(medium, outputstream);
LOG(WARNING) << "Created the virtual socket for Medium: " LOG(WARNING) << "Created the virtual socket for Medium: "
<< Medium_Name(virtual_socket->GetMedium()); << Medium_Name(virtual_socket->GetMedium());
if (virtual_sockets_ptr_ == nullptr) { if (virtual_sockets_ptr_ == nullptr) {
virtual_sockets_ptr_ = virtual_sockets_ptr; virtual_sockets_ptr_ = virtual_sockets_ptr;
} }
(*virtual_sockets_ptr_)[salted_service_id_hash_key] = virtual_socket; (*virtual_sockets_ptr_)[salted_service_id_hash_key] = virtual_socket;
LOG(INFO) << "virtual_sockets_ size: " LOG(INFO) << "virtual_sockets_ size: " << virtual_sockets_ptr_->size();
<< virtual_sockets_ptr_->size();
return virtual_socket.get(); return virtual_socket.get();
} }
void FeedIncomingData(ByteArray data) override { void FeedIncomingData(ByteArray data) override {
bytes_read_future_.Set(data); bytes_read_future_.Set(data);
LOG(INFO) << "FeedIncomingData. Size of receive data: " LOG(INFO) << "FeedIncomingData. Size of receive data: " << data.size()
<< data.size() << ", bytes content:" << std::string(data); << ", bytes content:" << std::string(data);
} }
bool IsVirtualSocket() override { return is_virtual_socket_; } bool IsVirtualSocket() override { return is_virtual_socket_; }
@@ -155,8 +153,7 @@ class FakeSocket : public MediumSocket {
}; };
TEST(MultiplexSocketTest, CreateSuccessAndReaderThreadStarted) { TEST(MultiplexSocketTest, CreateSuccessAndReaderThreadStarted) {
auto fake_socket_ptr = auto fake_socket_ptr = std::make_shared<FakeSocket>(Medium::BLUETOOTH);
std::make_shared<FakeSocket>(Medium::BLUETOOTH);
MultiplexSocket::StopListeningForIncomingConnection(std::string(SERVICE_ID_1), MultiplexSocket::StopListeningForIncomingConnection(std::string(SERVICE_ID_1),
Medium::BLUETOOTH); Medium::BLUETOOTH);
MultiplexSocket* multiplex_socket_incoming = MultiplexSocket* multiplex_socket_incoming =
@@ -204,8 +201,7 @@ TEST(MultiplexSocketTest, CreateSuccessAndReaderThreadStarted) {
EXPECT_EQ(multiplex_socket_incoming->GetVirtualSocketCount(), 0); EXPECT_EQ(multiplex_socket_incoming->GetVirtualSocketCount(), 0);
} }
TEST(MultiplexSocketTest, CreateFail_MediumNotSupport) { TEST(MultiplexSocketTest, CreateFail_MediumNotSupport) {
auto fake_socket_ptr = auto fake_socket_ptr = std::make_shared<FakeSocket>(Medium::WEB_RTC);
std::make_shared<FakeSocket>(Medium::WEB_RTC);
MultiplexSocket::StopListeningForIncomingConnection(std::string(SERVICE_ID_1), MultiplexSocket::StopListeningForIncomingConnection(std::string(SERVICE_ID_1),
Medium::WEB_RTC); Medium::WEB_RTC);
MultiplexSocket* multiplex_socket_incoming = MultiplexSocket* multiplex_socket_incoming =
@@ -231,9 +227,8 @@ TEST(MultiplexSocketTest,
multiplex_socket->EstablishVirtualSocket(std::string(SERVICE_ID_2)); multiplex_socket->EstablishVirtualSocket(std::string(SERVICE_ID_2));
EXPECT_EQ(socket, nullptr); EXPECT_EQ(socket, nullptr);
absl::SleepFor(absl::Milliseconds(100)); absl::SleepFor(absl::Milliseconds(100));
FakeSocket* virtual_socket = FakeSocket* virtual_socket = (FakeSocket*)multiplex_socket->GetVirtualSocket(
(FakeSocket*)multiplex_socket->GetVirtualSocket( std::string(SERVICE_ID_1));
std::string(SERVICE_ID_1));
if (virtual_socket == nullptr) { if (virtual_socket == nullptr) {
LOG(INFO) << "Virtual socket not found for " << SERVICE_ID_1; LOG(INFO) << "Virtual socket not found for " << SERVICE_ID_1;
return; return;
@@ -278,8 +273,7 @@ TEST(MultiplexSocketTest,
LOG(INFO) << "reader_2_ Read start"; LOG(INFO) << "reader_2_ Read start";
ExceptionOr<std::int32_t> read_int = Base64Utils::ReadInt(reader); ExceptionOr<std::int32_t> read_int = Base64Utils::ReadInt(reader);
if (!read_int.ok()) { if (!read_int.ok()) {
ADD_FAILURE() << "Failed to read. Exception:" ADD_FAILURE() << "Failed to read. Exception:" << read_int.exception();
<< read_int.exception();
} }
auto length = read_int.result(); auto length = read_int.result();
LOG(INFO) << " length:" << length; LOG(INFO) << " length:" << length;
@@ -294,8 +288,7 @@ TEST(MultiplexSocketTest,
EXPECT_EQ(multiplex_socket->GetVirtualSocketCount(), 0); EXPECT_EQ(multiplex_socket->GetVirtualSocketCount(), 0);
} }
TEST(MultiplexSocketTest, TEST(MultiplexSocketTest, EstablishVirtualSocket_RemoteAccepted) {
EstablishVirtualSocket_RemoteAccepted) {
auto fake_socket_ptr = std::make_shared<FakeSocket>(Medium::BLUETOOTH); auto fake_socket_ptr = std::make_shared<FakeSocket>(Medium::BLUETOOTH);
MultiplexSocket::StopListeningForIncomingConnection(std::string(SERVICE_ID_1), MultiplexSocket::StopListeningForIncomingConnection(std::string(SERVICE_ID_1),
Medium::BLUETOOTH); Medium::BLUETOOTH);
@@ -339,8 +332,7 @@ TEST(MultiplexSocketTest,
ADD_FAILURE() << "Invalid frame length:" << length; ADD_FAILURE() << "Invalid frame length:" << length;
} }
ExceptionOr<MultiplexFrame> frame_exc = ExceptionOr<MultiplexFrame> frame_exc = multiplex::FromBytes(bytes.result());
multiplex::FromBytes(bytes.result());
if (!frame_exc.ok()) { if (!frame_exc.ok()) {
ADD_FAILURE() << "Failed to parse MultiplexFrame. Exception:" ADD_FAILURE() << "Failed to parse MultiplexFrame. Exception:"
<< frame_exc.exception(); << frame_exc.exception();
@@ -356,7 +348,7 @@ TEST(MultiplexSocketTest,
ASSERT_EQ(control_frame.control_frame_type(), ASSERT_EQ(control_frame.control_frame_type(),
MultiplexControlFrame::CONNECTION_REQUEST); MultiplexControlFrame::CONNECTION_REQUEST);
LOG(INFO) << "Recieved MultiplexControlFrame::CONNECTION_REQUEST " LOG(INFO) << "Recieved MultiplexControlFrame::CONNECTION_REQUEST "
"frame, now send CONNECTION_RESPONSE frame."; "frame, now send CONNECTION_RESPONSE frame.";
ByteArray connection_response_frame = ByteArray connection_response_frame =
ForConnectionResponse(salted_service_id_hash, service_id_hash_salt, ForConnectionResponse(salted_service_id_hash, service_id_hash_salt,
+46 -67
View File
@@ -103,14 +103,13 @@ bool WebRtc::StartAcceptingConnections(const std::string& service_id,
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!IsAvailable()) { if (!IsAvailable()) {
LOG(WARNING) << "Cannot start accepting WebRTC connections because " LOG(WARNING) << "Cannot start accepting WebRTC connections because "
"WebRTC is not available."; "WebRTC is not available.";
return false; return false;
} }
if (IsAcceptingConnectionsLocked(service_id)) { if (IsAcceptingConnectionsLocked(service_id)) {
LOG(WARNING) LOG(WARNING) << "Cannot start accepting WebRTC connections because service "
<< "Cannot start accepting WebRTC connections because service " << service_id << "is already accepting WebRTC connections.";
<< service_id << "is already accepting WebRTC connections.";
return false; return false;
} }
@@ -151,16 +150,15 @@ bool WebRtc::StartAcceptingConnections(const std::string& service_id,
// a successful result. // a successful result.
accepting_connections_info_.emplace(service_id, std::move(info)); accepting_connections_info_.emplace(service_id, std::move(info));
LOG(INFO) << "Started listening for WebRTC connections as " LOG(INFO) << "Started listening for WebRTC connections as "
<< self_peer_id.GetId() << " on service " << service_id; << self_peer_id.GetId() << " on service " << service_id;
return true; return true;
} }
void WebRtc::StopAcceptingConnections(const std::string& service_id) { void WebRtc::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!IsAcceptingConnectionsLocked(service_id)) { if (!IsAcceptingConnectionsLocked(service_id)) {
LOG(WARNING) LOG(WARNING) << "Cannot stop accepting WebRTC connections because service "
<< "Cannot stop accepting WebRTC connections because service " << service_id << "is not accepting WebRTC connections.";
<< service_id << "is not accepting WebRTC connections.";
return; return;
} }
@@ -206,7 +204,7 @@ void WebRtc::StopAcceptingConnections(const std::string& service_id) {
// Clean up our state. We're now no longer listening for connections. // Clean up our state. We're now no longer listening for connections.
accepting_connections_info_.erase(service_id); accepting_connections_info_.erase(service_id);
LOG(INFO) << "Stopped listening for WebRTC connections for service " LOG(INFO) << "Stopped listening for WebRTC connections for service "
<< service_id; << service_id;
} }
ErrorOr<WebRtcSocketWrapper> WebRtc::Connect( ErrorOr<WebRtcSocketWrapper> WebRtc::Connect(
@@ -220,18 +218,17 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::Connect(
while (service_id_to_connect_attempts_count_map_[service_id] <= while (service_id_to_connect_attempts_count_map_[service_id] <=
kConnectAttemptsLimit) { kConnectAttemptsLimit) {
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(WARNING) LOG(WARNING) << "Attempt #"
<< "Attempt #" << service_id_to_connect_attempts_count_map_[service_id]
<< service_id_to_connect_attempts_count_map_[service_id] << ": Cannot Connect with WebRtc due to cancel.";
<< ": Cannot Connect with WebRtc due to cancel.";
return { return {
Error(OperationResultCode:: Error(OperationResultCode::
CLIENT_CANCELLATION_CANCEL_WEB_RTC_OUTGOING_CONNECTION)}; CLIENT_CANCELLATION_CANCEL_WEB_RTC_OUTGOING_CONNECTION)};
} }
LOG(INFO) << "Attempt #" LOG(INFO) << "Attempt #"
<< service_id_to_connect_attempts_count_map_[service_id] << service_id_to_connect_attempts_count_map_[service_id]
<< ": Beginning connection."; << ": Beginning connection.";
wrapper_result = AttemptToConnect(service_id, remote_peer_id, location_hint, wrapper_result = AttemptToConnect(service_id, remote_peer_id, location_hint,
cancellation_flag); cancellation_flag);
if (wrapper_result.has_value()) { if (wrapper_result.has_value()) {
@@ -241,8 +238,7 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::Connect(
service_id_to_connect_attempts_count_map_[service_id]++; service_id_to_connect_attempts_count_map_[service_id]++;
} }
LOG(WARNING) << "Giving up after " << kConnectAttemptsLimit LOG(WARNING) << "Giving up after " << kConnectAttemptsLimit << " attempts";
<< " attempts";
return {Error(wrapper_result.error().operation_result_code().value())}; return {Error(wrapper_result.error().operation_result_code().value())};
} }
@@ -259,19 +255,17 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::AttemptToConnect(
// is complete. // is complete.
CancellationFlagListener listener( CancellationFlagListener listener(
cancellation_flag, [this, &service_id, &socket_future]() { cancellation_flag, [this, &service_id, &socket_future]() {
LOG(WARNING) LOG(WARNING) << "Attempt # "
<< "Attempt # " << service_id_to_connect_attempts_count_map_[service_id]
<< service_id_to_connect_attempts_count_map_[service_id] << " to connect with WebRtc stopped due to cancel.";
<< " to connect with WebRtc stopped due to cancel.";
socket_future.SetException({Exception::kFailed}); socket_future.SetException({Exception::kFailed});
}); });
{ {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!IsAvailable()) { if (!IsAvailable()) {
LOG(WARNING) << "Cannot connect to WebRTC peer " LOG(WARNING) << "Cannot connect to WebRTC peer " << remote_peer_id.GetId()
<< remote_peer_id.GetId() << " because WebRTC is not available.";
<< " because WebRTC is not available.";
return { return {
Error(OperationResultCode::MEDIUM_UNAVAILABLE_WEB_RTC_NOT_AVAILABLE)}; Error(OperationResultCode::MEDIUM_UNAVAILABLE_WEB_RTC_NOT_AVAILABLE)};
} }
@@ -280,9 +274,8 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::AttemptToConnect(
std::unique_ptr<ConnectionFlow> connection_flow = std::unique_ptr<ConnectionFlow> connection_flow =
CreateConnectionFlow(service_id, remote_peer_id); CreateConnectionFlow(service_id, remote_peer_id);
if (!connection_flow) { if (!connection_flow) {
LOG(INFO) << "Cannot connect to WebRTC peer " LOG(INFO) << "Cannot connect to WebRTC peer " << remote_peer_id.GetId()
<< remote_peer_id.GetId() << " because we failed to create a ConnectionFlow.";
<< " because we failed to create a ConnectionFlow.";
return {Error(OperationResultCode::NEARBY_WEB_RTC_CONNECTION_FLOW_NULL)}; return {Error(OperationResultCode::NEARBY_WEB_RTC_CONNECTION_FLOW_NULL)};
} }
@@ -290,9 +283,8 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::AttemptToConnect(
info.signaling_messenger = medium_->GetSignalingMessenger( info.signaling_messenger = medium_->GetSignalingMessenger(
info.self_peer_id.GetId(), location_hint); info.self_peer_id.GetId(), location_hint);
if (!info.signaling_messenger->IsValid()) { if (!info.signaling_messenger->IsValid()) {
LOG(INFO) << "Cannot connect to WebRTC peer " LOG(INFO) << "Cannot connect to WebRTC peer " << remote_peer_id.GetId()
<< remote_peer_id.GetId() << " because we failed to create a SignalingMessenger.";
<< " because we failed to create a SignalingMessenger.";
return { return {
Error(OperationResultCode:: Error(OperationResultCode::
MISCELLEANEOUS_WEB_RTC_TACHYON_SIGNALING_MESSENGER_NULL)}; MISCELLEANEOUS_WEB_RTC_TACHYON_SIGNALING_MESSENGER_NULL)};
@@ -320,9 +312,8 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::AttemptToConnect(
if (!info.signaling_messenger->SendMessage( if (!info.signaling_messenger->SendMessage(
remote_peer_id.GetId(), remote_peer_id.GetId(),
webrtc_frames::EncodeReadyForSignalingPoke(info.self_peer_id))) { webrtc_frames::EncodeReadyForSignalingPoke(info.self_peer_id))) {
LOG(INFO) << "Cannot connect to WebRTC peer " LOG(INFO) << "Cannot connect to WebRTC peer " << remote_peer_id.GetId()
<< remote_peer_id.GetId() << " because we failed to poke the peer over Tachyon.";
<< " because we failed to poke the peer over Tachyon.";
info.signaling_messenger.reset(); info.signaling_messenger.reset();
return {Error(OperationResultCode:: return {Error(OperationResultCode::
CONNECTIVITY_WEB_RTC_CONNECT_TO_TACHYON_FAILURE)}; CONNECTIVITY_WEB_RTC_CONNECT_TO_TACHYON_FAILURE)};
@@ -352,7 +343,7 @@ ErrorOr<WebRtcSocketWrapper> WebRtc::AttemptToConnect(
// Verify that the connection went through. // Verify that the connection went through.
if (!socket_result.ok()) { if (!socket_result.ok()) {
LOG(INFO) << "Failed to connect to WebRTC peer " LOG(INFO) << "Failed to connect to WebRTC peer "
<< remote_peer_id.GetId(); << remote_peer_id.GetId();
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
info.signaling_messenger.reset(); info.signaling_messenger.reset();
requesting_connections_info_.erase(remote_peer_id.GetId()); requesting_connections_info_.erase(remote_peer_id.GetId());
@@ -385,8 +376,7 @@ void WebRtc::ProcessLocalIceCandidate(
webrtc_frames::EncodeIceCandidates( webrtc_frames::EncodeIceCandidates(
connection_request_entry->second.self_peer_id, connection_request_entry->second.self_peer_id,
{ice_candidate}))) { {ice_candidate}))) {
LOG(INFO) << "Failed to send ice candidate to " LOG(INFO) << "Failed to send ice candidate to " << remote_peer_id.GetId();
<< remote_peer_id.GetId();
} }
LOG(INFO) << "Sent ice candidate to " << remote_peer_id.GetId(); LOG(INFO) << "Sent ice candidate to " << remote_peer_id.GetId();
@@ -405,8 +395,7 @@ void WebRtc::ProcessLocalIceCandidate(
webrtc_frames::EncodeIceCandidates( webrtc_frames::EncodeIceCandidates(
accepting_connection_entry->second.self_peer_id, accepting_connection_entry->second.self_peer_id,
{ice_candidate}))) { {ice_candidate}))) {
LOG(INFO) << "Failed to send ice candidate to " LOG(INFO) << "Failed to send ice candidate to " << remote_peer_id.GetId();
<< remote_peer_id.GetId();
} }
LOG(INFO) << "Sent ice candidate to " << remote_peer_id.GetId(); LOG(INFO) << "Sent ice candidate to " << remote_peer_id.GetId();
@@ -414,8 +403,8 @@ void WebRtc::ProcessLocalIceCandidate(
} }
LOG(INFO) << "Skipping restart listening for tachyon inbox messages " LOG(INFO) << "Skipping restart listening for tachyon inbox messages "
"since we are not accepting connections for service " "since we are not accepting connections for service "
<< service_id; << service_id;
} }
void WebRtc::OnSignalingMessage(const std::string& service_id, void WebRtc::OnSignalingMessage(const std::string& service_id,
@@ -508,23 +497,20 @@ void WebRtc::SendOffer(const std::string& service_id,
std::unique_ptr<ConnectionFlow> connection_flow = std::unique_ptr<ConnectionFlow> connection_flow =
CreateConnectionFlow(service_id, remote_peer_id); CreateConnectionFlow(service_id, remote_peer_id);
if (!connection_flow) { if (!connection_flow) {
LOG(INFO) LOG(INFO) << "Unable to send offer. Failed to create a ConnectionFlow.";
<< "Unable to send offer. Failed to create a ConnectionFlow.";
return; return;
} }
SessionDescriptionWrapper offer = connection_flow->CreateOffer(); SessionDescriptionWrapper offer = connection_flow->CreateOffer();
if (!offer.IsValid()) { if (!offer.IsValid()) {
LOG(INFO) LOG(INFO) << "Unable to send offer. Failed to create our offer locally.";
<< "Unable to send offer. Failed to create our offer locally.";
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
return; return;
} }
const webrtc::SessionDescriptionInterface& sdp = offer.GetSdp(); const webrtc::SessionDescriptionInterface& sdp = offer.GetSdp();
if (!connection_flow->SetLocalSessionDescription(offer)) { if (!connection_flow->SetLocalSessionDescription(offer)) {
LOG(INFO) LOG(INFO) << "Unable to send offer. Failed to register our offer locally.";
<< "Unable to send offer. Failed to register our offer locally.";
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
return; return;
} }
@@ -552,14 +538,12 @@ void WebRtc::ReceiveOffer(const WebrtcPeerId& remote_peer_id,
SessionDescriptionWrapper offer) { SessionDescriptionWrapper offer) {
const auto& entry = connection_flows_.find(remote_peer_id.GetId()); const auto& entry = connection_flows_.find(remote_peer_id.GetId());
if (entry == connection_flows_.end()) { if (entry == connection_flows_.end()) {
LOG(INFO) LOG(INFO) << "Unable to receive offer. Failed to create a ConnectionFlow.";
<< "Unable to receive offer. Failed to create a ConnectionFlow.";
return; return;
} }
if (!entry->second->OnOfferReceived(offer)) { if (!entry->second->OnOfferReceived(offer)) {
LOG(INFO) LOG(INFO) << "Unable to receive offer. Failed to process the offer.";
<< "Unable to receive offer. Failed to process the offer.";
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
} }
} }
@@ -567,15 +551,13 @@ void WebRtc::ReceiveOffer(const WebrtcPeerId& remote_peer_id,
void WebRtc::SendAnswer(const WebrtcPeerId& remote_peer_id) { void WebRtc::SendAnswer(const WebrtcPeerId& remote_peer_id) {
const auto& entry = connection_flows_.find(remote_peer_id.GetId()); const auto& entry = connection_flows_.find(remote_peer_id.GetId());
if (entry == connection_flows_.end()) { if (entry == connection_flows_.end()) {
LOG(INFO) LOG(INFO) << "Unable to send answer. Failed to create a ConnectionFlow.";
<< "Unable to send answer. Failed to create a ConnectionFlow.";
return; return;
} }
SessionDescriptionWrapper answer = entry->second->CreateAnswer(); SessionDescriptionWrapper answer = entry->second->CreateAnswer();
if (!answer.IsValid()) { if (!answer.IsValid()) {
LOG(INFO) LOG(INFO) << "Unable to send answer. Failed to create our answer locally.";
<< "Unable to send answer. Failed to create our answer locally.";
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
return; return;
} }
@@ -593,7 +575,7 @@ void WebRtc::SendAnswer(const WebrtcPeerId& remote_peer_id) {
requesting_connections_info_.find(remote_peer_id.GetId()); requesting_connections_info_.find(remote_peer_id.GetId());
if (connection_request_entry == requesting_connections_info_.end()) { if (connection_request_entry == requesting_connections_info_.end()) {
LOG(INFO) << "Unable to send answer. Failed to find an outgoing " LOG(INFO) << "Unable to send answer. Failed to find an outgoing "
"connection request."; "connection request.";
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
return; return;
} }
@@ -618,14 +600,12 @@ void WebRtc::ReceiveAnswer(const WebrtcPeerId& remote_peer_id,
SessionDescriptionWrapper answer) { SessionDescriptionWrapper answer) {
const auto& entry = connection_flows_.find(remote_peer_id.GetId()); const auto& entry = connection_flows_.find(remote_peer_id.GetId());
if (entry == connection_flows_.end()) { if (entry == connection_flows_.end()) {
LOG(INFO) LOG(INFO) << "Unable to receive answer. Failed to create a ConnectionFlow.";
<< "Unable to receive answer. Failed to create a ConnectionFlow.";
return; return;
} }
if (!entry->second->OnAnswerReceived(answer)) { if (!entry->second->OnAnswerReceived(answer)) {
LOG(INFO) LOG(INFO) << "Unable to receive answer. Failed to process the answer.";
<< "Unable to receive answer. Failed to process the answer.";
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
} }
} }
@@ -637,7 +617,7 @@ void WebRtc::ReceiveIceCandidates(
const auto& entry = connection_flows_.find(remote_peer_id.GetId()); const auto& entry = connection_flows_.find(remote_peer_id.GetId());
if (entry == connection_flows_.end()) { if (entry == connection_flows_.end()) {
LOG(INFO) << "Unable to receive ice candidates. Failed to create a " LOG(INFO) << "Unable to receive ice candidates. Failed to create a "
"ConnectionFlow."; "ConnectionFlow.";
return; return;
} }
@@ -677,8 +657,8 @@ void WebRtc::RestartTachyonReceiveMessages(const std::string& service_id) {
} }
LOG(INFO) << "Successfully restarted listening for tachyon inbox " LOG(INFO) << "Successfully restarted listening for tachyon inbox "
"messages on service " "messages on service "
<< service_id; << service_id;
} }
void WebRtc::ProcessDataChannelOpen(const std::string& service_id, void WebRtc::ProcessDataChannelOpen(const std::string& service_id,
@@ -706,15 +686,14 @@ void WebRtc::ProcessDataChannelOpen(const std::string& service_id,
// No one to handle the newly created DataChannel, so we'll just close it. // No one to handle the newly created DataChannel, so we'll just close it.
socket_wrapper.Close(); socket_wrapper.Close();
LOG(INFO) << "Ignoring new DataChannel because we are not accepting " LOG(INFO) << "Ignoring new DataChannel because we are not accepting "
"connections for service " "connections for service "
<< service_id; << service_id;
} }
void WebRtc::ProcessDataChannelClosed(const WebrtcPeerId& remote_peer_id) { void WebRtc::ProcessDataChannelClosed(const WebrtcPeerId& remote_peer_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) LOG(INFO) << "Data channel has closed, removing connection flow for peer "
<< "Data channel has closed, removing connection flow for peer " << remote_peer_id.GetId();
<< remote_peer_id.GetId();
RemoveConnectionFlow(remote_peer_id); RemoveConnectionFlow(remote_peer_id);
} }
@@ -71,7 +71,7 @@ class CreateSessionDescriptionObserverImpl
void OnFailure(webrtc::RTCError error) override { void OnFailure(webrtc::RTCError error) override {
LOG(ERROR) << "Error when creating session description: " LOG(ERROR) << "Error when creating session description: "
<< error.message(); << error.message();
settable_future_.SetException({Exception::kFailed}); settable_future_.SetException({Exception::kFailed});
} }
@@ -252,7 +252,7 @@ bool ConnectionFlow::SetLocalSessionDescription(SessionDescriptionWrapper sdp) {
bool success = result.ok() && result.result(); bool success = result.ok() && result.result();
if (!success) { if (!success) {
LOG(ERROR) << "Failed to set local session description: " LOG(ERROR) << "Failed to set local session description: "
<< result.exception(); << result.exception();
} }
return success; return success;
} }
@@ -284,8 +284,7 @@ bool ConnectionFlow::SetRemoteSessionDescription(SessionDescriptionWrapper sdp,
ExceptionOr<bool> result = observer->GetResult(kTimeout); ExceptionOr<bool> result = observer->GetResult(kTimeout);
bool success = result.ok() && result.result(); bool success = result.ok() && result.result();
if (!success) { if (!success) {
LOG(ERROR) << "Failed to set remote description: " LOG(ERROR) << "Failed to set remote description: " << result.exception();
<< result.exception();
} }
return success; return success;
} }
@@ -330,8 +329,7 @@ void ConnectionFlow::AddIceCandidatesOnSignalingThread(
ice_candidates) { ice_candidates) {
CHECK(IsRunningOnSignalingThread()); CHECK(IsRunningOnSignalingThread());
if (state_ == State::kEnded) { if (state_ == State::kEnded) {
LOG(WARNING) LOG(WARNING) << "You cannot add ice candidates to a disconnected session.";
<< "You cannot add ice candidates to a disconnected session.";
return; return;
} }
if (state_ != State::kWaitingToConnect && state_ != State::kConnected) { if (state_ != State::kWaitingToConnect && state_ != State::kConnected) {
@@ -397,8 +395,7 @@ bool ConnectionFlow::InitPeerConnection(WebRtcMedium& webrtc_medium) {
bool success = result.ok() && result.result(); bool success = result.ok() && result.result();
if (!success) { if (!success) {
shutdown_latch_.CountDown(); shutdown_latch_.CountDown();
LOG(ERROR) << "Failed to create peer connection: " LOG(ERROR) << "Failed to create peer connection: " << result.exception();
<< result.exception();
} }
return success; return success;
} }
@@ -424,7 +421,7 @@ void ConnectionFlow::CreateSocketFromDataChannel(
CHECK(IsRunningOnSignalingThread()); CHECK(IsRunningOnSignalingThread());
if (!TransitionState(State::kWaitingToConnect, State::kConnected)) { if (!TransitionState(State::kWaitingToConnect, State::kConnected)) {
LOG(ERROR) << "Data channel socket is open but connection " LOG(ERROR) << "Data channel socket is open but connection "
"flow was not in the required state"; "flow was not in the required state";
socket->Close(); socket->Close();
return; return;
} }
@@ -475,7 +472,7 @@ void ConnectionFlow::OnConnectionChange(
new_state == PeerConnectionState::kFailed || new_state == PeerConnectionState::kFailed ||
new_state == PeerConnectionState::kDisconnected) { new_state == PeerConnectionState::kDisconnected) {
LOG(INFO) << "Closing due to peer connection state change: " LOG(INFO) << "Closing due to peer connection state change: "
<< static_cast<int>(new_state); << static_cast<int>(new_state);
CloseOnSignalingThread(); CloseOnSignalingThread();
} }
} }
@@ -499,13 +496,13 @@ bool ConnectionFlow::TransitionState(State current_state, State new_state) {
CHECK(IsRunningOnSignalingThread()); CHECK(IsRunningOnSignalingThread());
if (current_state != state_) { if (current_state != state_) {
LOG(WARNING) << "Invalid state transition to " LOG(WARNING) << "Invalid state transition to "
<< static_cast<int>(new_state) << ": current state is " << static_cast<int>(new_state) << ": current state is "
<< static_cast<int>(state_) << " but expected " << static_cast<int>(state_) << " but expected "
<< static_cast<int>(current_state); << static_cast<int>(current_state);
return false; return false;
} }
LOG(INFO) << "Transition: " << static_cast<int>(state_) << "->" LOG(INFO) << "Transition: " << static_cast<int>(state_) << "->"
<< static_cast<int>(new_state); << static_cast<int>(new_state);
state_ = new_state; state_ = new_state;
return true; return true;
} }
@@ -540,25 +537,24 @@ bool ConnectionFlow::RunOnSignalingThread(Runnable&& runnable) {
CHECK(!IsRunningOnSignalingThread()); CHECK(!IsRunningOnSignalingThread());
auto pc = GetPeerConnection(); auto pc = GetPeerConnection();
if (!pc) { if (!pc) {
LOG(WARNING) LOG(WARNING) << "Peer connection not available. Cannot schedule tasks.";
<< "Peer connection not available. Cannot schedule tasks.";
return false; return false;
} }
// We are off signaling thread, so we can't use peer connection's methods // We are off signaling thread, so we can't use peer connection's methods
// but we can access the signaling thread handle. // but we can access the signaling thread handle.
pc->signaling_thread()->PostTask([can_run_tasks = pc->signaling_thread()->PostTask(
std::weak_ptr<void>(can_run_tasks_), [can_run_tasks = std::weak_ptr<void>(can_run_tasks_),
task = std::move(runnable)]() mutable { task = std::move(runnable)]() mutable {
// Don't run the task if the weak_ptr is no longer valid. // Don't run the task if the weak_ptr is no longer valid.
// shared_ptr |can_run_tasks_| is destroyed on the same thread // shared_ptr |can_run_tasks_| is destroyed on the same thread
// (signaling thread). This guarantees that if the weak_ptr is valid // (signaling thread). This guarantees that if the weak_ptr is valid
// when this task starts, it will stay valid until the task ends. // when this task starts, it will stay valid until the task ends.
if (!can_run_tasks.lock()) { if (!can_run_tasks.lock()) {
LOG(INFO) << "Peer connection already closed. Cannot run tasks."; LOG(INFO) << "Peer connection already closed. Cannot run tasks.";
return; return;
} }
task(); task();
}); });
return true; return true;
} }
@@ -67,23 +67,21 @@ WebRtcSocket::WebRtcSocket(
const std::string& name, const std::string& name,
webrtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) webrtc::scoped_refptr<webrtc::DataChannelInterface> data_channel)
: name_(name), data_channel_(std::move(data_channel)) { : name_(name), data_channel_(std::move(data_channel)) {
LOG(INFO) << "WebRtcSocket::WebRtcSocket(" << name_ LOG(INFO) << "WebRtcSocket::WebRtcSocket(" << name_ << ") this: " << this;
<< ") this: " << this;
std::tie(pipe_input_, pipe_output_) = CreatePipe(); std::tie(pipe_input_, pipe_output_) = CreatePipe();
data_channel_->RegisterObserver(this); data_channel_->RegisterObserver(this);
} }
WebRtcSocket::~WebRtcSocket() { WebRtcSocket::~WebRtcSocket() {
LOG(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_ LOG(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_ << ") this: " << this;
<< ") this: " << this;
if (!IsClosed()) { if (!IsClosed()) {
data_channel_->UnregisterObserver(); data_channel_->UnregisterObserver();
Close(); Close();
} }
LOG(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_ LOG(INFO) << "WebRtcSocket::~WebRtcSocket(" << name_ << ") this: " << this
<< ") this: " << this << " done"; << " done";
} }
InputStream& WebRtcSocket::GetInputStream() { return *pipe_input_; } InputStream& WebRtcSocket::GetInputStream() { return *pipe_input_; }
@@ -99,16 +97,15 @@ Exception WebRtcSocket::Close() {
// to 'closing' but does not block until 'closed' is sent so the data channel // to 'closing' but does not block until 'closed' is sent so the data channel
// is not fully closed when this call is done. // is not fully closed when this call is done.
data_channel_->Close(); data_channel_->Close();
LOG(INFO) << "WebRtcSocket::Close(" << name_ << ") this: " << this LOG(INFO) << "WebRtcSocket::Close(" << name_ << ") this: " << this << " done";
<< " done";
return {Exception::kSuccess}; return {Exception::kSuccess};
} }
void WebRtcSocket::OnStateChange() { void WebRtcSocket::OnStateChange() {
// Running on the signaling thread right now. // Running on the signaling thread right now.
LOG(ERROR) LOG(ERROR) << "WebRtcSocket::OnStateChange() webrtc data channel state: "
<< "WebRtcSocket::OnStateChange() webrtc data channel state: " << webrtc::DataChannelInterface::DataStateString(
<< webrtc::DataChannelInterface::DataStateString(data_channel_->state()); data_channel_->state());
switch (data_channel_->state()) { switch (data_channel_->state()) {
case webrtc::DataChannelInterface::DataState::kConnecting: case webrtc::DataChannelInterface::DataState::kConnecting:
break; break;
@@ -121,7 +118,7 @@ void WebRtcSocket::OnStateChange() {
break; break;
case webrtc::DataChannelInterface::DataState::kClosed: case webrtc::DataChannelInterface::DataState::kClosed:
LOG(ERROR) << "WebRtcSocket::OnStateChange() unregistering data " LOG(ERROR) << "WebRtcSocket::OnStateChange() unregistering data "
"channel observer."; "channel observer.";
// This will trigger a destruction of the owning connection flow // This will trigger a destruction of the owning connection flow
// We implicitly depend on the |socket_listener_| to offload from // We implicitly depend on the |socket_listener_| to offload from
// the signaling thread so it does not get blocked. // the signaling thread so it does not get blocked.
@@ -163,8 +160,7 @@ bool WebRtcSocket::SendMessage(const ByteArray& data) {
bool WebRtcSocket::IsClosed() { return closed_.Get(); } bool WebRtcSocket::IsClosed() { return closed_.Get(); }
void WebRtcSocket::ClosePipe() { void WebRtcSocket::ClosePipe() {
LOG(INFO) << "WebRtcSocket::ClosePipe(" << name_ LOG(INFO) << "WebRtcSocket::ClosePipe(" << name_ << ") this: " << this;
<< ") this: " << this;
// This is thread-safe to close these sockets even if a read or write is in // This is thread-safe to close these sockets even if a read or write is in
// process on another thread, Close will wait for the exclusive mutex before // process on another thread, Close will wait for the exclusive mutex before
// setting state. // setting state.
@@ -172,7 +168,7 @@ void WebRtcSocket::ClosePipe() {
pipe_output_->Close(); pipe_output_->Close();
WakeUpWriter(); WakeUpWriter();
LOG(INFO) << "WebRtcSocket::ClosePipe(" << name_ << ") this: " << this LOG(INFO) << "WebRtcSocket::ClosePipe(" << name_ << ") this: " << this
<< " done"; << " done";
} }
// Must not be called on signalling thread. // Must not be called on signalling thread.
@@ -22,8 +22,8 @@
#include "internal/platform/expected.h" #include "internal/platform/expected.h"
#include "internal/platform/logging.h" #include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h" #include "internal/platform/mutex_lock.h"
#include "internal/platform/wifi_direct.h"
#include "internal/platform/wifi_credential.h" #include "internal/platform/wifi_credential.h"
#include "internal/platform/wifi_direct.h"
namespace nearby { namespace nearby {
namespace connections { namespace connections {
@@ -106,8 +106,7 @@ bool WifiDirect::ConnectWifiDirect(const std::string& ssid,
const std::string& password) { const std::string& password) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (is_connected_to_go_) { if (is_connected_to_go_) {
LOG(INFO) LOG(INFO) << "No need to connect to GO because it is already connected.";
<< "No need to connect to GO because it is already connected.";
return true; return true;
} }
is_connected_to_go_ = medium_.ConnectWifiDirect(ssid, password); is_connected_to_go_ = medium_.ConnectWifiDirect(ssid, password);
@@ -117,8 +116,7 @@ bool WifiDirect::ConnectWifiDirect(const std::string& ssid,
bool WifiDirect::DisconnectWifiDirect() { bool WifiDirect::DisconnectWifiDirect() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!is_connected_to_go_) { if (!is_connected_to_go_) {
LOG(INFO) LOG(INFO) << "No need to disconnect to GO because it is not connected.";
<< "No need to disconnect to GO because it is not connected.";
return true; return true;
} }
is_connected_to_go_ = false; is_connected_to_go_ = false;
@@ -134,7 +132,7 @@ WifiDirectCredentials* WifiDirect::GetCredentials(
const auto& it = server_sockets_.find(service_id); const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) { if (it == server_sockets_.end()) {
LOG(INFO) << "No server socket found for service_id:" << service_id LOG(INFO) << "No server socket found for service_id:" << service_id
<< ". Use default credentials"; << ". Use default credentials";
return crendential; return crendential;
} }
crendential->SetGateway(it->second.GetIPAddress()); crendential->SetGateway(it->second.GetIPAddress());
@@ -149,9 +147,8 @@ bool WifiDirect::StartAcceptingConnections(
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) LOG(INFO) << "Can not to start accepting WifiDirect GC's connections; "
<< "Can not to start accepting WifiDirect GC's connections; " "service_id is empty.";
"service_id is empty.";
return false; return false;
} }
@@ -211,16 +208,15 @@ bool WifiDirect::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) LOG(INFO) << "Unable to stop accepting WifiDirect GC's connections because "
<< "Unable to stop accepting WifiDirect GC's connections because " "the service_id is empty.";
"the service_id is empty.";
return false; return false;
} }
const auto& it = server_sockets_.find(service_id); const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) { if (it == server_sockets_.end()) {
LOG(INFO) << "Can't stop accepting WifiDirect GC's connections for " LOG(INFO) << "Can't stop accepting WifiDirect GC's connections for "
<< service_id << " because it was never started."; << service_id << " because it was never started.";
return false; return false;
} }
@@ -241,9 +237,8 @@ bool WifiDirect::StopAcceptingConnections(const std::string& service_id) {
// Finally, close the WifiDirectServerSocket. // Finally, close the WifiDirectServerSocket.
if (!listening_socket.Close().Ok()) { if (!listening_socket.Close().Ok()) {
LOG(INFO) LOG(INFO) << "Failed to close WifiDirect server socket for service_id:"
<< "Failed to close WifiDirect server socket for service_id:" << service_id;
<< service_id;
return false; return false;
} }
@@ -268,13 +263,13 @@ ErrorOr<WifiDirectSocket> WifiDirect::Connect(
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Refusing to create client WifiDirect socket because " LOG(INFO) << "Refusing to create client WifiDirect socket because "
"service_id is empty."; "service_id is empty.";
return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)}; return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)};
} }
if (!IsGCAvailableLocked()) { if (!IsGCAvailableLocked()) {
LOG(INFO) << "Can't create WifiDirect client socket [service_id=" LOG(INFO) << "Can't create WifiDirect client socket [service_id="
<< service_id << "]; WifiDirect GC isn't available."; << service_id << "]; WifiDirect GC isn't available.";
return {Error( return {Error(
OperationResultCode::MEDIUM_UNAVAILABLE_WIFI_DIRECT_NOT_AVAILABLE)}; OperationResultCode::MEDIUM_UNAVAILABLE_WIFI_DIRECT_NOT_AVAILABLE)};
} }
@@ -289,7 +284,7 @@ ErrorOr<WifiDirectSocket> WifiDirect::Connect(
socket = medium_.ConnectToService(ip_address, port, cancellation_flag); socket = medium_.ConnectToService(ip_address, port, cancellation_flag);
if (!socket.IsValid()) { if (!socket.IsValid()) {
LOG(INFO) << "Failed to Connect via WifiDirect Server [service_id=" LOG(INFO) << "Failed to Connect via WifiDirect Server [service_id="
<< service_id << "]"; << service_id << "]";
return {Error(OperationResultCode:: return {Error(OperationResultCode::
CONNECTIVITY_WIFI_DIRECT_CLIENT_SOCKET_CREATION_FAILURE)}; CONNECTIVITY_WIFI_DIRECT_CLIENT_SOCKET_CREATION_FAILURE)};
} }
@@ -75,8 +75,7 @@ bool WifiHotspot::IsHotspotStarted() {
bool WifiHotspot::StartWifiHotspot() { bool WifiHotspot::StartWifiHotspot() {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (is_hotspot_started_) { if (is_hotspot_started_) {
LOG(INFO) LOG(INFO) << "No need to start Hotspot because it is already started.";
<< "No need to start Hotspot because it is already started.";
return true; return true;
} }
is_hotspot_started_ = medium_.StartWifiHotspot(); is_hotspot_started_ = medium_.StartWifiHotspot();
@@ -132,7 +131,7 @@ HotspotCredentials* WifiHotspot::GetCredentials(absl::string_view service_id) {
const auto& it = server_sockets_.find(service_id); const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) { if (it == server_sockets_.end()) {
LOG(INFO) << "No server socket found for service_id:" << service_id LOG(INFO) << "No server socket found for service_id:" << service_id
<< ". Use default credentials"; << ". Use default credentials";
return crendential; return crendential;
} }
crendential->SetGateway(it->second.GetIPAddress()); crendential->SetGateway(it->second.GetIPAddress());
@@ -148,14 +147,13 @@ bool WifiHotspot::StartAcceptingConnections(
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Can not to start accepting WifiHotspot connections; " LOG(INFO) << "Can not to start accepting WifiHotspot connections; "
"service_id is empty."; "service_id is empty.";
return false; return false;
} }
if (!IsAPAvailableLocked()) { if (!IsAPAvailableLocked()) {
LOG(INFO) LOG(INFO) << "Can't start accepting WifiHotspot connections [service_id="
<< "Can't start accepting WifiHotspot connections [service_id=" << service_id << "]; WifiHotspot not available.";
<< service_id << "]; WifiHotspot not available.";
return false; return false;
} }
@@ -208,16 +206,15 @@ bool WifiHotspot::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) LOG(INFO) << "Unable to stop accepting WifiHotspot connections because "
<< "Unable to stop accepting WifiHotspot connections because " "the service_id is empty.";
"the service_id is empty.";
return false; return false;
} }
const auto& it = server_sockets_.find(service_id); const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) { if (it == server_sockets_.end()) {
LOG(INFO) << "Can't stop accepting WifiHotspot connections for " LOG(INFO) << "Can't stop accepting WifiHotspot connections for "
<< service_id << " because it was never started."; << service_id << " because it was never started.";
return false; return false;
} }
@@ -238,9 +235,8 @@ bool WifiHotspot::StopAcceptingConnections(const std::string& service_id) {
// Finally, close the WifiHotspotServerSocket. // Finally, close the WifiHotspotServerSocket.
if (!listening_socket.Close().Ok()) { if (!listening_socket.Close().Ok()) {
LOG(INFO) LOG(INFO) << "Failed to close WifiHotspot server socket for service_id:"
<< "Failed to close WifiHotspot server socket for service_id:" << service_id;
<< service_id;
return false; return false;
} }
@@ -265,13 +261,13 @@ ErrorOr<WifiHotspotSocket> WifiHotspot::Connect(
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Refusing to create client WifiHotspot socket because " LOG(INFO) << "Refusing to create client WifiHotspot socket because "
"service_id is empty."; "service_id is empty.";
return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)}; return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)};
} }
if (!IsClientAvailableLocked()) { if (!IsClientAvailableLocked()) {
LOG(INFO) << "Can't create client WifiHotspot socket [service_id=" LOG(INFO) << "Can't create client WifiHotspot socket [service_id="
<< service_id << "]; WifiHotspot isn't available."; << service_id << "]; WifiHotspot isn't available.";
return {Error( return {Error(
OperationResultCode::MEDIUM_UNAVAILABLE_WIFI_HOTSPOT_NOT_AVAILABLE)}; OperationResultCode::MEDIUM_UNAVAILABLE_WIFI_HOTSPOT_NOT_AVAILABLE)};
} }
@@ -285,8 +281,8 @@ ErrorOr<WifiHotspotSocket> WifiHotspot::Connect(
socket = medium_.ConnectToService(ip_address, port, cancellation_flag); socket = medium_.ConnectToService(ip_address, port, cancellation_flag);
if (!socket.IsValid()) { if (!socket.IsValid()) {
LOG(INFO) << "Failed to Connect via WifiHotspot [service_id=" LOG(INFO) << "Failed to Connect via WifiHotspot [service_id=" << service_id
<< service_id << "]"; << "]";
return { return {
Error(OperationResultCode:: Error(OperationResultCode::
CONNECTIVITY_WIFI_HOTSPOT_CLIENT_SOCKET_CREATION_FAILURE)}; CONNECTIVITY_WIFI_HOTSPOT_CLIENT_SOCKET_CREATION_FAILURE)};
+63 -78
View File
@@ -59,8 +59,8 @@ WifiLan::~WifiLan() {
{ {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (is_multiplex_enabled_) { if (is_multiplex_enabled_) {
LOG(INFO) << "Closing multiplex sockets for " LOG(INFO) << "Closing multiplex sockets for " << multiplex_sockets_.size()
<< multiplex_sockets_.size() << " IPs"; << " IPs";
for (auto& [ip_addr, multiplex_socket] : multiplex_sockets_) { for (auto& [ip_addr, multiplex_socket] : multiplex_sockets_) {
LOG(INFO) << "Closing multiplex sockets for: " << ip_addr; LOG(INFO) << "Closing multiplex sockets for: " << ip_addr;
multiplex_socket->~MultiplexSocket(); multiplex_socket->~MultiplexSocket();
@@ -87,8 +87,7 @@ ErrorOr<bool> WifiLan::StartAdvertising(const std::string& service_id,
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) LOG(INFO) << "Can't turn on WifiLan advertising. WifiLan is not available.";
<< "Can't turn on WifiLan advertising. WifiLan is not available.";
return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_LAN_NOT_AVAILABLE)}; return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_LAN_NOT_AVAILABLE)};
} }
@@ -106,12 +105,11 @@ ErrorOr<bool> WifiLan::StartAdvertising(const std::string& service_id,
} }
if (!IsAcceptingConnectionsLocked(service_id)) { if (!IsAcceptingConnectionsLocked(service_id)) {
LOG(INFO) LOG(INFO) << "Failed to turn on WifiLan advertising with nsd_service_info="
<< "Failed to turn on WifiLan advertising with nsd_service_info=" << &nsd_service_info
<< &nsd_service_info << ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_name=" << nsd_service_info.GetServiceName() << ", service_id=" << service_id
<< ", service_id=" << service_id << ". Should accept connections before advertising.";
<< ". Should accept connections before advertising.";
return {Error(OperationResultCode:: return {Error(OperationResultCode::
CLIENT_DUPLICATE_ACCEPTING_LAN_CONNECTION_REQUEST)}; CLIENT_DUPLICATE_ACCEPTING_LAN_CONNECTION_REQUEST)};
} }
@@ -123,19 +121,18 @@ ErrorOr<bool> WifiLan::StartAdvertising(const std::string& service_id,
nsd_service_info.SetPort(it->second.GetPort()); nsd_service_info.SetPort(it->second.GetPort());
} }
if (!medium_.StartAdvertising(nsd_service_info)) { if (!medium_.StartAdvertising(nsd_service_info)) {
LOG(INFO) LOG(INFO) << "Failed to turn on WifiLan advertising with nsd_service_info="
<< "Failed to turn on WifiLan advertising with nsd_service_info=" << &nsd_service_info
<< &nsd_service_info << ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_name=" << nsd_service_info.GetServiceName() << ", service_id=" << service_id;
<< ", service_id=" << service_id;
return {Error( return {Error(
OperationResultCode::CONNECTIVITY_WIFI_LAN_START_ADVERTISING_FAILURE)}; OperationResultCode::CONNECTIVITY_WIFI_LAN_START_ADVERTISING_FAILURE)};
} }
LOG(INFO) << "Turned on WifiLan advertising with nsd_service_info=" LOG(INFO) << "Turned on WifiLan advertising with nsd_service_info="
<< &nsd_service_info << &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName() << ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_id=" << service_id; << ", service_id=" << service_id;
advertising_info_.Add(service_id, std::move(nsd_service_info)); advertising_info_.Add(service_id, std::move(nsd_service_info));
return {true}; return {true};
} }
@@ -144,13 +141,11 @@ bool WifiLan::StopAdvertising(const std::string& service_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!IsAdvertisingLocked(service_id)) { if (!IsAdvertisingLocked(service_id)) {
LOG(INFO) LOG(INFO) << "Can't turn off WifiLan advertising; it is already off";
<< "Can't turn off WifiLan advertising; it is already off";
return false; return false;
} }
LOG(INFO) << "Turned off WifiLan advertising with service_id=" LOG(INFO) << "Turned off WifiLan advertising with service_id=" << service_id;
<< service_id;
bool ret = bool ret =
medium_.StopAdvertising(*advertising_info_.GetServiceInfo(service_id)); medium_.StopAdvertising(*advertising_info_.GetServiceInfo(service_id));
// Reset our bundle of advertising state to mark that we're no longer // Reset our bundle of advertising state to mark that we're no longer
@@ -174,8 +169,7 @@ ErrorOr<bool> WifiLan::StartDiscovery(const std::string& service_id,
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) LOG(INFO) << "Refusing to start WifiLan discovering with empty service_id.";
<< "Refusing to start WifiLan discovering with empty service_id.";
return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)}; return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)};
} }
@@ -202,8 +196,7 @@ ErrorOr<bool> WifiLan::StartDiscovery(const std::string& service_id,
OperationResultCode::CONNECTIVITY_WIFI_LAN_START_DISCOVERY_FAILURE)}; OperationResultCode::CONNECTIVITY_WIFI_LAN_START_DISCOVERY_FAILURE)};
} }
LOG(INFO) << "Turned on WifiLan discovering with service_id=" LOG(INFO) << "Turned on WifiLan discovering with service_id=" << service_id;
<< service_id;
// Mark the fact that we're currently performing a WifiLan discovering. // Mark the fact that we're currently performing a WifiLan discovering.
discovering_info_.Add(service_id); discovering_info_.Add(service_id);
return {true}; return {true};
@@ -213,15 +206,14 @@ bool WifiLan::StopDiscovery(const std::string& service_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (!IsDiscoveringLocked(service_id)) { if (!IsDiscoveringLocked(service_id)) {
LOG(INFO) LOG(INFO) << "Can't turn off WifiLan discovering because we never started "
<< "Can't turn off WifiLan discovering because we never started " "discovering.";
"discovering.";
return false; return false;
} }
std::string service_type = GenerateServiceType(service_id); std::string service_type = GenerateServiceType(service_id);
LOG(INFO) << "Turned off WifiLan discovering with service_id=" LOG(INFO) << "Turned off WifiLan discovering with service_id=" << service_id
<< service_id << ", service_type=" << service_type; << ", service_type=" << service_type;
bool ret = medium_.StopDiscovery(service_type); bool ret = medium_.StopDiscovery(service_type);
discovering_info_.Remove(service_id); discovering_info_.Remove(service_id);
return ret; return ret;
@@ -242,23 +234,21 @@ ErrorOr<bool> WifiLan::StartAcceptingConnections(
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Refusing to start accepting WifiLan connections; " LOG(INFO) << "Refusing to start accepting WifiLan connections; "
"service_id is empty."; "service_id is empty.";
return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)}; return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)};
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) LOG(INFO) << "Can't start accepting WifiLan connections [service_id="
<< "Can't start accepting WifiLan connections [service_id=" << service_id << "]; WifiLan not available.";
<< service_id << "]; WifiLan not available.";
return {Error( return {Error(
OperationResultCode::MEDIUM_UNAVAILABLE_WIFI_AWARE_NOT_AVAILABLE)}; OperationResultCode::MEDIUM_UNAVAILABLE_WIFI_AWARE_NOT_AVAILABLE)};
} }
if (IsAcceptingConnectionsLocked(service_id)) { if (IsAcceptingConnectionsLocked(service_id)) {
LOG(INFO) LOG(INFO) << "Refusing to start accepting WifiLan connections [service="
<< "Refusing to start accepting WifiLan connections [service=" << service_id
<< service_id << "]; WifiLan server is already in-progress with the same name.";
<< "]; WifiLan server is already in-progress with the same name.";
return {Error(OperationResultCode:: return {Error(OperationResultCode::
CLIENT_DUPLICATE_ACCEPTING_LAN_CONNECTION_REQUEST)}; CLIENT_DUPLICATE_ACCEPTING_LAN_CONNECTION_REQUEST)};
} }
@@ -275,9 +265,8 @@ ErrorOr<bool> WifiLan::StartAcceptingConnections(
} }
WifiLanServerSocket server_socket = medium_.ListenForService(port); WifiLanServerSocket server_socket = medium_.ListenForService(port);
if (!server_socket.IsValid()) { if (!server_socket.IsValid()) {
LOG(INFO) LOG(INFO) << "Failed to start accepting WifiLan connections for service_id="
<< "Failed to start accepting WifiLan connections for service_id=" << service_id;
<< service_id;
return {Error(OperationResultCode:: return {Error(OperationResultCode::
CLIENT_CANCELLATION_WIFI_LAN_SERVER_SOCKET_CREATION)}; CLIENT_CANCELLATION_WIFI_LAN_SERVER_SOCKET_CREATION)};
} }
@@ -351,7 +340,7 @@ ErrorOr<bool> WifiLan::StartAcceptingConnections(
MultiplexSocket::StopListeningForIncomingConnection( MultiplexSocket::StopListeningForIncomingConnection(
service_id, Medium::WIFI_LAN); service_id, Medium::WIFI_LAN);
LOG(INFO) << "Multiplex virtaul socket created for " LOG(INFO) << "Multiplex virtaul socket created for "
<< server_socket.GetIPAddress(); << server_socket.GetIPAddress();
if (callback) { if (callback) {
callback( callback(
service_id, service_id,
@@ -377,14 +366,14 @@ bool WifiLan::StopAcceptingConnections(const std::string& service_id) {
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Unable to stop accepting WifiLan connections because " LOG(INFO) << "Unable to stop accepting WifiLan connections because "
"the service_id is empty."; "the service_id is empty.";
return false; return false;
} }
const auto& it = server_sockets_.find(service_id); const auto& it = server_sockets_.find(service_id);
if (it == server_sockets_.end()) { if (it == server_sockets_.end()) {
LOG(INFO) << "Can't stop accepting WifiLan connections for " LOG(INFO) << "Can't stop accepting WifiLan connections for " << service_id
<< service_id << " because it was never started."; << " because it was never started.";
return false; return false;
} }
if (is_multiplex_enabled_) { if (is_multiplex_enabled_) {
@@ -410,7 +399,7 @@ bool WifiLan::StopAcceptingConnections(const std::string& service_id) {
// Finally, close the WifiLanServerSocket. // Finally, close the WifiLanServerSocket.
if (!listening_socket.Close().Ok()) { if (!listening_socket.Close().Ok()) {
LOG(INFO) << "Failed to close WifiLan server socket for service_id=" LOG(INFO) << "Failed to close WifiLan server socket for service_id="
<< service_id; << service_id;
return false; return false;
} }
@@ -435,13 +424,13 @@ ErrorOr<WifiLanSocket> WifiLan::Connect(const std::string& service_id,
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Refusing to create client WifiLan socket because " LOG(INFO) << "Refusing to create client WifiLan socket because "
"service_id is empty."; "service_id is empty.";
return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)}; return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)};
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) << "Can't create client WifiLan socket [service_id=" LOG(INFO) << "Can't create client WifiLan socket [service_id=" << service_id
<< service_id << "]; WifiLan isn't available."; << "]; WifiLan isn't available.";
return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_LAN_NOT_AVAILABLE)}; return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_LAN_NOT_AVAILABLE)};
} }
@@ -459,8 +448,8 @@ ErrorOr<WifiLanSocket> WifiLan::Connect(const std::string& service_id,
socket = medium_.ConnectToService(service_info, cancellation_flag); socket = medium_.ConnectToService(service_info, cancellation_flag);
if (!socket.IsValid()) { if (!socket.IsValid()) {
LOG(INFO) << "Failed to Connect via WifiLan [service_id=" LOG(INFO) << "Failed to Connect via WifiLan [service_id=" << service_id
<< service_id << "]"; << "]";
return {Error( return {Error(
OperationResultCode::CONNECTIVITY_LAN_CLIENT_SOCKET_CREATION_FAILURE)}; OperationResultCode::CONNECTIVITY_LAN_CLIENT_SOCKET_CREATION_FAILURE)};
} else { } else {
@@ -468,15 +457,14 @@ ErrorOr<WifiLanSocket> WifiLan::Connect(const std::string& service_id,
CreateOutgoingMultiplexSocketLocked(socket, service_id, CreateOutgoingMultiplexSocketLocked(socket, service_id,
service_info.GetIPAddress()); service_info.GetIPAddress());
if (virtual_socket.ok()) { if (virtual_socket.ok()) {
LOG(INFO) LOG(INFO) << "Successfully connected via Multiplex WifiLan [service_id="
<< "Successfully connected via Multiplex WifiLan [service_id=" << service_id << "]";
<< service_id << "]";
return virtual_socket.result(); return virtual_socket.result();
} }
} }
LOG(INFO) << "Successfully connected via WifiLan [service_id=" LOG(INFO) << "Successfully connected via WifiLan [service_id=" << service_id
<< service_id << "]"; << "]";
return socket; return socket;
} }
@@ -489,13 +477,13 @@ ErrorOr<WifiLanSocket> WifiLan::Connect(const std::string& service_id,
if (service_id.empty()) { if (service_id.empty()) {
LOG(INFO) << "Refusing to create client WifiLan socket because " LOG(INFO) << "Refusing to create client WifiLan socket because "
"service_id is empty."; "service_id is empty.";
return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)}; return {Error(OperationResultCode::NEARBY_LOCAL_CLIENT_STATE_WRONG)};
} }
if (!IsAvailableLocked()) { if (!IsAvailableLocked()) {
LOG(INFO) << "Can't create client WifiLan socket [service_id=" LOG(INFO) << "Can't create client WifiLan socket [service_id=" << service_id
<< service_id << "]; WifiLan isn't available."; << "]; WifiLan isn't available.";
return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_LAN_NOT_AVAILABLE)}; return {Error(OperationResultCode::MEDIUM_UNAVAILABLE_LAN_NOT_AVAILABLE)};
} }
@@ -513,38 +501,35 @@ ErrorOr<WifiLanSocket> WifiLan::Connect(const std::string& service_id,
socket = medium_.ConnectToService(ip_address, port, cancellation_flag); socket = medium_.ConnectToService(ip_address, port, cancellation_flag);
if (!socket.IsValid()) { if (!socket.IsValid()) {
LOG(INFO) << "Failed to Connect via WifiLan [service_id=" LOG(INFO) << "Failed to Connect via WifiLan [service_id=" << service_id
<< service_id << "]"; << "]";
return {Error( return {Error(
OperationResultCode::CONNECTIVITY_LAN_CLIENT_SOCKET_CREATION_FAILURE)}; OperationResultCode::CONNECTIVITY_LAN_CLIENT_SOCKET_CREATION_FAILURE)};
} else { } else {
ExceptionOr<WifiLanSocket> virtual_socket = ExceptionOr<WifiLanSocket> virtual_socket =
CreateOutgoingMultiplexSocketLocked(socket, service_id, ip_address); CreateOutgoingMultiplexSocketLocked(socket, service_id, ip_address);
if (virtual_socket.ok()) { if (virtual_socket.ok()) {
LOG(INFO) LOG(INFO) << "Successfully connected via Multiplex WifiLan [service_id="
<< "Successfully connected via Multiplex WifiLan [service_id=" << service_id << "]";
<< service_id << "]";
return virtual_socket.result(); return virtual_socket.result();
} }
} }
LOG(INFO) << "Successfully connected via WifiLan [service_id=" LOG(INFO) << "Successfully connected via WifiLan [service_id=" << service_id
<< service_id << "]"; << "]";
return socket; return socket;
} }
ExceptionOr<WifiLanSocket> WifiLan::ConnectWithMultiplexSocketLocked( ExceptionOr<WifiLanSocket> WifiLan::ConnectWithMultiplexSocketLocked(
const std::string& service_id, const std::string& ip_address) { const std::string& service_id, const std::string& ip_address) {
if (is_multiplex_enabled_) { if (is_multiplex_enabled_) {
LOG(INFO) << "multiplex_sockets_ size:" LOG(INFO) << "multiplex_sockets_ size:" << multiplex_sockets_.size();
<< multiplex_sockets_.size();
auto it = multiplex_sockets_.find(ip_address); auto it = multiplex_sockets_.find(ip_address);
if (it != multiplex_sockets_.end()) { if (it != multiplex_sockets_.end()) {
MultiplexSocket* multiplex_socket = it->second; MultiplexSocket* multiplex_socket = it->second;
if (multiplex_socket->IsShutdown()) { if (multiplex_socket->IsShutdown()) {
LOG(INFO) LOG(INFO) << "Erase multiplex_socket(already shutdown) for ip_address: "
<< "Erase multiplex_socket(already shutdown) for ip_address: " << WifiUtils::GetHumanReadableIpAddress(ip_address);
<< WifiUtils::GetHumanReadableIpAddress(ip_address);
multiplex_socket->~MultiplexSocket(); multiplex_socket->~MultiplexSocket();
multiplex_sockets_.erase(it); multiplex_sockets_.erase(it);
return ExceptionOr<WifiLanSocket>(Exception::kFailed); return ExceptionOr<WifiLanSocket>(Exception::kFailed);
@@ -555,9 +540,9 @@ ExceptionOr<WifiLanSocket> WifiLan::ConnectWithMultiplexSocketLocked(
// Should not happen. // Should not happen.
auto* wlan_socket = down_cast<WifiLanSocket*>(virtual_socket); auto* wlan_socket = down_cast<WifiLanSocket*>(virtual_socket);
if (wlan_socket == nullptr) { if (wlan_socket == nullptr) {
LOG(INFO) << "Failed to cast to WifiLanSocket for " LOG(INFO) << "Failed to cast to WifiLanSocket for " << service_id
<< service_id << " with ip_address: " << " with ip_address: "
<< WifiUtils::GetHumanReadableIpAddress(ip_address); << WifiUtils::GetHumanReadableIpAddress(ip_address);
return ExceptionOr<WifiLanSocket>(Exception::kFailed); return ExceptionOr<WifiLanSocket>(Exception::kFailed);
} }
return ExceptionOr<WifiLanSocket>(*wlan_socket); return ExceptionOr<WifiLanSocket>(*wlan_socket);
@@ -582,12 +567,12 @@ ExceptionOr<WifiLanSocket> WifiLan::CreateOutgoingMultiplexSocketLocked(
auto* wlan_socket = down_cast<WifiLanSocket*>(virtual_socket); auto* wlan_socket = down_cast<WifiLanSocket*>(virtual_socket);
if (wlan_socket == nullptr) { if (wlan_socket == nullptr) {
LOG(INFO) << "Failed to cast to WifiLanSocket for " << service_id LOG(INFO) << "Failed to cast to WifiLanSocket for " << service_id
<< " with ip_address: " << " with ip_address: "
<< WifiUtils::GetHumanReadableIpAddress(ip_address); << WifiUtils::GetHumanReadableIpAddress(ip_address);
return ExceptionOr<WifiLanSocket>(Exception::kFailed); return ExceptionOr<WifiLanSocket>(Exception::kFailed);
} }
LOG(INFO) << "Multiplex socket created for ip_address: " LOG(INFO) << "Multiplex socket created for ip_address: "
<< WifiUtils::GetHumanReadableIpAddress(ip_address); << WifiUtils::GetHumanReadableIpAddress(ip_address);
multiplex_sockets_.emplace(ip_address, multiplex_socket); multiplex_sockets_.emplace(ip_address, multiplex_socket);
return ExceptionOr<WifiLanSocket>(*wlan_socket); return ExceptionOr<WifiLanSocket>(*wlan_socket);
} }
@@ -93,8 +93,7 @@ TEST_P(WifiLanTest, CanConnect) {
.service_discovered_cb = .service_discovered_cb =
[&discovered_latch, &discovered_service_info]( [&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info, const std::string& service_id) { NsdServiceInfo service_info, const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Discovered service_info=" << &service_info;
<< "Discovered service_info=" << &service_info;
discovered_service_info = service_info; discovered_service_info = service_info;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
@@ -162,7 +161,7 @@ TEST_P(WifiLanTest, CanConnectWithMultiplex) {
NsdServiceInfo service_info, NsdServiceInfo service_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) << "Discovered service_info=" LOG(INFO) << "Discovered service_info="
<< &service_info; << &service_info;
discovered_service_info = service_info; discovered_service_info = service_info;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
@@ -224,8 +223,7 @@ TEST_P(WifiLanTest, CanCancelConnect) {
.service_discovered_cb = .service_discovered_cb =
[&discovered_latch, &discovered_service_info]( [&discovered_latch, &discovered_service_info](
NsdServiceInfo service_info, const std::string& service_id) { NsdServiceInfo service_info, const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Discovered service_info=" << &service_info;
<< "Discovered service_info=" << &service_info;
discovered_service_info = service_info; discovered_service_info = service_info;
discovered_latch.CountDown(); discovered_latch.CountDown();
}, },
@@ -54,8 +54,7 @@ Status OfflineServiceController::StartAdvertising(
const ConnectionRequestInfo& info) { const ConnectionRequestInfo& info) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to start advertising for service_id " << " requested to start advertising for service_id " << service_id;
<< service_id;
return pcp_manager_.StartAdvertising(client, service_id, advertising_options, return pcp_manager_.StartAdvertising(client, service_id, advertising_options,
info); info);
} }
@@ -63,8 +62,8 @@ Status OfflineServiceController::StartAdvertising(
void OfflineServiceController::StopAdvertising(ClientProxy* client) { void OfflineServiceController::StopAdvertising(ClientProxy* client) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to stop advertising for service_id " << " requested to stop advertising for service_id "
<< client->GetAdvertisingServiceId(); << client->GetAdvertisingServiceId();
pcp_manager_.StopAdvertising(client); pcp_manager_.StopAdvertising(client);
} }
@@ -73,8 +72,7 @@ Status OfflineServiceController::StartDiscovery(
const DiscoveryOptions& discovery_options, DiscoveryListener listener) { const DiscoveryOptions& discovery_options, DiscoveryListener listener) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to start discovery for service_id " << " requested to start discovery for service_id " << service_id;
<< service_id;
return pcp_manager_.StartDiscovery(client, service_id, discovery_options, return pcp_manager_.StartDiscovery(client, service_id, discovery_options,
std::move(listener)); std::move(listener));
} }
@@ -82,8 +80,8 @@ Status OfflineServiceController::StartDiscovery(
void OfflineServiceController::StopDiscovery(ClientProxy* client) { void OfflineServiceController::StopDiscovery(ClientProxy* client) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to stop discovery for service_id " << " requested to stop discovery for service_id "
<< client->GetDiscoveryServiceId(); << client->GetDiscoveryServiceId();
pcp_manager_.StopDiscovery(client); pcp_manager_.StopDiscovery(client);
} }
@@ -93,8 +91,7 @@ OfflineServiceController::StartListeningForIncomingConnections(
v3::ConnectionListener listener, v3::ConnectionListener listener,
const v3::ConnectionListeningOptions& options) { const v3::ConnectionListeningOptions& options) {
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to start listening for service_id " << " requested to start listening for service_id " << service_id;
<< service_id;
return pcp_manager_.StartListeningForIncomingConnections( return pcp_manager_.StartListeningForIncomingConnections(
client, service_id, std::move(listener), options); client, service_id, std::move(listener), options);
} }
@@ -102,8 +99,8 @@ OfflineServiceController::StartListeningForIncomingConnections(
void OfflineServiceController::StopListeningForIncomingConnections( void OfflineServiceController::StopListeningForIncomingConnections(
ClientProxy* client) { ClientProxy* client) {
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to stop listening for service_id " << " requested to stop listening for service_id "
<< client->GetListeningForIncomingConnectionsServiceId(); << client->GetListeningForIncomingConnectionsServiceId();
pcp_manager_.StopListeningForIncomingConnections(client); pcp_manager_.StopListeningForIncomingConnections(client);
} }
@@ -112,12 +109,12 @@ void OfflineServiceController::InjectEndpoint(
const OutOfBandConnectionMetadata& metadata) { const OutOfBandConnectionMetadata& metadata) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to inject endpoint {endpoint_id:" << " requested to inject endpoint {endpoint_id:"
<< metadata.endpoint_id << ", endpoint_info:" << metadata.endpoint_id
<< metadata.endpoint_info.AsStringView() << ", endpoint_info:" << metadata.endpoint_info.AsStringView()
<< ",remote_bluetooth_mac_address:" << ",remote_bluetooth_mac_address:"
<< metadata.remote_bluetooth_mac_address.AsStringView() << metadata.remote_bluetooth_mac_address.AsStringView()
<< "} for service_id " << service_id; << "} for service_id " << service_id;
pcp_manager_.InjectEndpoint(client, service_id, metadata); pcp_manager_.InjectEndpoint(client, service_id, metadata);
} }
@@ -127,7 +124,7 @@ Status OfflineServiceController::RequestConnection(
const ConnectionOptions& connection_options) { const ConnectionOptions& connection_options) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested a connection to endpoint_id " << endpoint_id; << " requested a connection to endpoint_id " << endpoint_id;
return pcp_manager_.RequestConnection(client, endpoint_id, info, return pcp_manager_.RequestConnection(client, endpoint_id, info,
connection_options); connection_options);
} }
@@ -138,8 +135,8 @@ Status OfflineServiceController::RequestConnectionV3(
const ConnectionOptions& connection_options) { const ConnectionOptions& connection_options) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested a connection to endpoint_id " << " requested a connection to endpoint_id "
<< remote_device.GetEndpointId(); << remote_device.GetEndpointId();
return pcp_manager_.RequestConnectionV3(client, remote_device, info, return pcp_manager_.RequestConnectionV3(client, remote_device, info,
connection_options); connection_options);
} }
@@ -149,8 +146,7 @@ Status OfflineServiceController::AcceptConnection(
PayloadListener listener) { PayloadListener listener) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " accepted the connection from endpoint_id " << " accepted the connection from endpoint_id " << endpoint_id;
<< endpoint_id;
return pcp_manager_.AcceptConnection(client, endpoint_id, return pcp_manager_.AcceptConnection(client, endpoint_id,
std::move(listener)); std::move(listener));
} }
@@ -159,8 +155,7 @@ Status OfflineServiceController::RejectConnection(
ClientProxy* client, const std::string& endpoint_id) { ClientProxy* client, const std::string& endpoint_id) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " rejected the connection from endpoint_id " << " rejected the connection from endpoint_id " << endpoint_id;
<< endpoint_id;
return pcp_manager_.RejectConnection(client, endpoint_id); return pcp_manager_.RejectConnection(client, endpoint_id);
} }
@@ -168,8 +163,8 @@ void OfflineServiceController::InitiateBandwidthUpgrade(
ClientProxy* client, const std::string& endpoint_id) { ClientProxy* client, const std::string& endpoint_id) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " initiated a manual bandwidth upgrade with endpoint_id " << " initiated a manual bandwidth upgrade with endpoint_id "
<< endpoint_id; << endpoint_id;
bwu_manager_.InitiateBwuForEndpoint(client, endpoint_id); bwu_manager_.InitiateBwuForEndpoint(client, endpoint_id);
} }
@@ -178,17 +173,17 @@ void OfflineServiceController::SendPayload(
Payload payload) { Payload payload) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " is sending payload {id:" << payload.GetId() << " is sending payload {id:" << payload.GetId()
<< ", type:" << payload.GetType() << "} to endpoint_ids {" << ", type:" << payload.GetType() << "} to endpoint_ids {"
<< absl::StrJoin(endpoint_ids, ",") << "}"; << absl::StrJoin(endpoint_ids, ",") << "}";
payload_manager_.SendPayload(client, endpoint_ids, std::move(payload)); payload_manager_.SendPayload(client, endpoint_ids, std::move(payload));
} }
Status OfflineServiceController::CancelPayload(ClientProxy* client, Status OfflineServiceController::CancelPayload(ClientProxy* client,
std::int64_t payload_id) { std::int64_t payload_id) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId() << " cancelled payload "
<< " cancelled payload " << payload_id; << payload_id;
return payload_manager_.CancelPayload(client, payload_id); return payload_manager_.CancelPayload(client, payload_id);
} }
@@ -196,8 +191,7 @@ void OfflineServiceController::DisconnectFromEndpoint(
ClientProxy* client, const std::string& endpoint_id) { ClientProxy* client, const std::string& endpoint_id) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested a disconnection from endpoint_id " << " requested a disconnection from endpoint_id " << endpoint_id;
<< endpoint_id;
endpoint_manager_.UnregisterEndpoint(client, endpoint_id); endpoint_manager_.UnregisterEndpoint(client, endpoint_id);
} }
@@ -205,10 +199,9 @@ Status OfflineServiceController::UpdateAdvertisingOptions(
ClientProxy* client, absl::string_view service_id, ClientProxy* client, absl::string_view service_id,
const AdvertisingOptions& advertising_options) { const AdvertisingOptions& advertising_options) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) LOG(INFO) << "Client " << client->GetClientId()
<< "Client " << client->GetClientId() << " requested to update advertising options for service_id "
<< " requested to update advertising options for service_id " << service_id;
<< service_id;
return pcp_manager_.UpdateAdvertisingOptions(client, service_id, return pcp_manager_.UpdateAdvertisingOptions(client, service_id,
advertising_options); advertising_options);
} }
@@ -218,8 +211,8 @@ Status OfflineServiceController::UpdateDiscoveryOptions(
const DiscoveryOptions& discovery_options) { const DiscoveryOptions& discovery_options) {
if (stop_) return {Status::kOutOfOrderApiCall}; if (stop_) return {Status::kOutOfOrderApiCall};
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to update discovery options for service_id " << " requested to update discovery options for service_id "
<< service_id; << service_id;
return pcp_manager_.UpdateDiscoveryOptions(client, service_id, return pcp_manager_.UpdateDiscoveryOptions(client, service_id,
discovery_options); discovery_options);
} }
@@ -228,7 +221,7 @@ void OfflineServiceController::SetCustomSavePath(ClientProxy* client,
const std::string& path) { const std::string& path) {
if (stop_) return; if (stop_) return;
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " requested to set custom save path to " << path; << " requested to set custom save path to " << path;
payload_manager_.SetCustomSavePath(client, path); payload_manager_.SetCustomSavePath(client, path);
} }
@@ -97,7 +97,8 @@ class OfflineServiceControllerTest
config_package_nearby::nearby_connections_feature::kEnableBleV2, true); config_package_nearby::nearby_connections_feature::kEnableBleV2, true);
NearbyFlags::GetInstance().OverrideBoolFlagValue( NearbyFlags::GetInstance().OverrideBoolFlagValue(
config_package_nearby::nearby_connections_feature:: config_package_nearby::nearby_connections_feature::
kEnableSafeToDisconnect, false); kEnableSafeToDisconnect,
false);
} }
bool SetupConnection(OfflineSimulationUser& user_a, bool SetupConnection(OfflineSimulationUser& user_a,
OfflineSimulationUser& user_b) { OfflineSimulationUser& user_b) {
@@ -107,13 +108,11 @@ class OfflineServiceControllerTest
EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId); EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo()); EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty()); EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
LOG(INFO) << "EP-B: [discovered] " LOG(INFO) << "EP-B: [discovered] " << user_b.GetDiscovered().endpoint_id;
<< user_b.GetDiscovered().endpoint_id;
user_b.RequestConnection(&connect_latch_); user_b.RequestConnection(&connect_latch_);
EXPECT_TRUE(connect_latch_.Await(kLongTimeout)); EXPECT_TRUE(connect_latch_.Await(kLongTimeout));
EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty()); EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
LOG(INFO) << "EP-A: [discovered] " LOG(INFO) << "EP-A: [discovered] " << user_a.GetDiscovered().endpoint_id;
<< user_a.GetDiscovered().endpoint_id;
LOG(INFO) << "Both users discovered their peers."; LOG(INFO) << "Both users discovered their peers.";
user_a.AcceptConnection(&accept_latch_); user_a.AcceptConnection(&accept_latch_);
user_b.AcceptConnection(&accept_latch_); user_b.AcceptConnection(&accept_latch_);
@@ -54,8 +54,7 @@ void OfflineSimulationUser::OnConnectionRejected(const std::string& endpoint_id,
void OfflineSimulationUser::OnEndpointDisconnect( void OfflineSimulationUser::OnEndpointDisconnect(
const std::string& endpoint_id) { const std::string& endpoint_id) {
LOG(INFO) << "OnEndpointDisconnect: self=" << this LOG(INFO) << "OnEndpointDisconnect: self=" << this << "; id=" << endpoint_id;
<< "; id=" << endpoint_id;
if (disconnect_latch_) disconnect_latch_->CountDown(); if (disconnect_latch_) disconnect_latch_->CountDown();
} }
@@ -213,8 +213,7 @@ TEST_F(P2pClusterPcpHandlerTest,
[&latch](const std::string& endpoint_id, [&latch](const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id;
<< "Device discovered: id=" << endpoint_id;
latch.CountDown(); latch.CountDown();
}, },
}), }),
@@ -268,7 +267,7 @@ class P2pClusterPcpHandlerTestWithParam
} }
LOG(INFO) << "SetUp: ble v2 enabled: " << ble_v2_enabled; LOG(INFO) << "SetUp: ble v2 enabled: " << ble_v2_enabled;
LOG(INFO) << "SetUp: is_disable_bluetooth_scanning: " LOG(INFO) << "SetUp: is_disable_bluetooth_scanning: "
<< is_disable_bluetooth_scanning; << is_disable_bluetooth_scanning;
LOG(INFO) << "SetUp: end"; LOG(INFO) << "SetUp: end";
} }
@@ -562,8 +561,7 @@ TEST_P(P2pClusterPcpHandlerTestWithParam, CanDiscover) {
[&latch](const std::string& endpoint_id, [&latch](const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id;
<< "Device discovered: id=" << endpoint_id;
latch.CountDown(); latch.CountDown();
}, },
}), }),
@@ -602,8 +600,7 @@ TEST_P(P2pClusterPcpHandlerTestWithParam, CanDiscoverLegacy) {
[&latch](const std::string& endpoint_id, [&latch](const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id;
<< "Device discovered: id=" << endpoint_id;
latch.CountDown(); latch.CountDown();
}, },
}), }),
@@ -687,8 +684,7 @@ TEST_P(P2pClusterPcpHandlerTestWithParam, ResumeBluetoothClassicDiscovery) {
[&latch](const std::string& endpoint_id, [&latch](const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id;
<< "Device discovered: id=" << endpoint_id;
latch.CountDown(); latch.CountDown();
}, },
}), }),
@@ -765,8 +761,7 @@ TEST_P(P2pClusterPcpHandlerTestWithParam, CanBluetoothDiscoverChangeName) {
[&](const std::string& endpoint_id, [&](const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id;
<< "Device discovered: id=" << endpoint_id;
if (!first) { if (!first) {
first_found_latch.CountDown(); first_found_latch.CountDown();
first = true; first = true;
@@ -1011,10 +1006,9 @@ TEST_P(P2pClusterPcpHandlerTestWithParam, CanConnect) {
const std::string& endpoint_id, const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id
<< "Device discovered: id=" << endpoint_id << ", endpoint_info="
<< ", endpoint_info=" << std::string{endpoint_info};
<< std::string{endpoint_info};
discovered = { discovered = {
.endpoint_id = endpoint_id, .endpoint_id = endpoint_id,
.endpoint_info = endpoint_info, .endpoint_info = endpoint_info,
@@ -1047,8 +1041,7 @@ TEST_P(P2pClusterPcpHandlerTestWithParam, CanConnect) {
.initiated_cb = .initiated_cb =
[&connect_latch](const std::string& endpoint_id, [&connect_latch](const std::string& endpoint_id,
const ConnectionResponseInfo& info) { const ConnectionResponseInfo& info) {
LOG(INFO) LOG(INFO) << "RequestConnection: initiated_cb called";
<< "RequestConnection: initiated_cb called";
connect_latch.CountDown(); connect_latch.CountDown();
}, },
}}, }},
@@ -21,7 +21,6 @@
#include <tuple> #include <tuple>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "absl/time/time.h" #include "absl/time/time.h"
#include "connections/advertising_options.h" #include "connections/advertising_options.h"
#include "connections/connection_options.h" #include "connections/connection_options.h"
@@ -199,10 +198,9 @@ TEST_P(P2pPointToPointPcpHandlerTest, CanConnect) {
const std::string& endpoint_id, const std::string& endpoint_id,
const ByteArray& endpoint_info, const ByteArray& endpoint_info,
const std::string& service_id) { const std::string& service_id) {
LOG(INFO) LOG(INFO) << "Device discovered: id=" << endpoint_id
<< "Device discovered: id=" << endpoint_id << ", endpoint_info="
<< ", endpoint_info=" << endpoint_info.AsStringView();
<< endpoint_info.AsStringView();
discovered = { discovered = {
.endpoint_id = endpoint_id, .endpoint_id = endpoint_id,
.endpoint_info = endpoint_info, .endpoint_info = endpoint_info,
@@ -235,8 +233,7 @@ TEST_P(P2pPointToPointPcpHandlerTest, CanConnect) {
.initiated_cb = .initiated_cb =
[&connect_latch](const std::string& endpoint_id, [&connect_latch](const std::string& endpoint_id,
const ConnectionResponseInfo& info) { const ConnectionResponseInfo& info) {
LOG(INFO) LOG(INFO) << "RequestConnection: initiated_cb called";
<< "RequestConnection: initiated_cb called";
connect_latch.CountDown(); connect_latch.CountDown();
}, },
}}, }},
@@ -41,8 +41,8 @@ namespace connections {
namespace { namespace {
using ::location::nearby::connections::OfflineFrame; using ::location::nearby::connections::OfflineFrame;
using ::location::nearby::connections::PayloadTransferFrame; using ::location::nearby::connections::PayloadTransferFrame;
using ::nearby::analytics::PacketMetaData;
using ::location::nearby::proto::connections::Medium; using ::location::nearby::proto::connections::Medium;
using ::nearby::analytics::PacketMetaData;
constexpr size_t kChunkSize = 64 * 1024; constexpr size_t kChunkSize = 64 * 1024;
constexpr absl::string_view kServiceId = "service-id"; constexpr absl::string_view kServiceId = "service-id";
@@ -148,13 +148,11 @@ class PayloadManagerTest
EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId); EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo()); EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty()); EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
LOG(INFO) << "EP-B: [discovered] " LOG(INFO) << "EP-B: [discovered] " << user_b.GetDiscovered().endpoint_id;
<< user_b.GetDiscovered().endpoint_id;
user_b.RequestConnection(&connection_latch_); user_b.RequestConnection(&connection_latch_);
EXPECT_TRUE(connection_latch_.Await(kDefaultTimeout).result()); EXPECT_TRUE(connection_latch_.Await(kDefaultTimeout).result());
EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty()); EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
LOG(INFO) << "EP-A: [discovered] " LOG(INFO) << "EP-A: [discovered] " << user_a.GetDiscovered().endpoint_id;
<< user_a.GetDiscovered().endpoint_id;
LOG(INFO) << "Both users discovered their peers."; LOG(INFO) << "Both users discovered their peers.";
user_a.AcceptConnection(&accept_latch_); user_a.AcceptConnection(&accept_latch_);
user_b.AcceptConnection(&accept_latch_); user_b.AcceptConnection(&accept_latch_);
+1 -1
View File
@@ -216,7 +216,7 @@ bool PcpManager::SetCurrentPcpHandler(Strategy strategy) {
if (!current_) { if (!current_) {
LOG(ERROR) << "Failed to set current PCP handler: strategy=" LOG(ERROR) << "Failed to set current PCP handler: strategy="
<< strategy.GetName(); << strategy.GetName();
} }
return current_; return current_;
@@ -41,9 +41,7 @@ constexpr absl::string_view kDeviceB = "device-b";
constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000); constexpr absl::Duration kDefaultTimeout = absl::Milliseconds(1000);
constexpr BooleanMediumSelector kTestCases[] = { constexpr BooleanMediumSelector kTestCases[] = {
BooleanMediumSelector{ BooleanMediumSelector{.bluetooth = true},
.bluetooth = true
},
}; };
class ReconnectSimulatorUser : public SimulationUser { class ReconnectSimulatorUser : public SimulationUser {
@@ -75,13 +73,11 @@ class ReconnectManagerTest
EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId); EXPECT_EQ(user_b.GetDiscovered().service_id, kServiceId);
EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo()); EXPECT_EQ(user_b.GetDiscovered().endpoint_info, user_a.GetInfo());
EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty()); EXPECT_FALSE(user_b.GetDiscovered().endpoint_id.empty());
LOG(INFO) << "EP-B: [discovered]" LOG(INFO) << "EP-B: [discovered]" << user_b.GetDiscovered().endpoint_id;
<< user_b.GetDiscovered().endpoint_id;
user_b.RequestConnection(&connection_latch_); user_b.RequestConnection(&connection_latch_);
EXPECT_TRUE(connection_latch_.Await(kDefaultTimeout).result()); EXPECT_TRUE(connection_latch_.Await(kDefaultTimeout).result());
EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty()); EXPECT_FALSE(user_a.GetDiscovered().endpoint_id.empty());
LOG(INFO) << "EP-A: [discovered]" LOG(INFO) << "EP-A: [discovered]" << user_a.GetDiscovered().endpoint_id;
<< user_a.GetDiscovered().endpoint_id;
LOG(INFO) << "Both users discovered their peers."; LOG(INFO) << "Both users discovered their peers.";
user_a.AcceptConnection(&accept_latch_); user_a.AcceptConnection(&accept_latch_);
user_b.AcceptConnection(&accept_latch_); user_b.AcceptConnection(&accept_latch_);
@@ -98,8 +94,8 @@ class ReconnectManagerTest
}; };
TEST_P(ReconnectManagerTest, AllowReconnect) { TEST_P(ReconnectManagerTest, AllowReconnect) {
FeatureFlags::Flags feature_flags = { FeatureFlags::Flags feature_flags = {.enable_cancellation_flag =
.enable_cancellation_flag = std::get<1>(GetParam())}; std::get<1>(GetParam())};
env_.SetFeatureFlags(feature_flags); env_.SetFeatureFlags(feature_flags);
env_.Start(); env_.Start();
@@ -111,15 +107,14 @@ TEST_P(ReconnectManagerTest, AllowReconnect) {
ReconnectManager::AutoReconnectCallback auto_reconnect_callback = { ReconnectManager::AutoReconnectCallback auto_reconnect_callback = {
.on_reconnect_success_cb = .on_reconnect_success_cb =
[&](ClientProxy* client, const std::string& endpoint_id) { [&](ClientProxy* client, const std::string& endpoint_id) {
LOG(INFO) LOG(INFO) << " Reconnect successfully for endpoint_id: "
<< " Reconnect successfully for endpoint_id: " << endpoint_id; << endpoint_id;
}, },
.on_reconnect_failure_cb = .on_reconnect_failure_cb =
[&](ClientProxy* client, const std::string& endpoint_id, [&](ClientProxy* client, const std::string& endpoint_id,
bool send_disconnection_notification, bool send_disconnection_notification,
DisconnectionReason disconnection_reason) { DisconnectionReason disconnection_reason) {
LOG(INFO) LOG(INFO) << " Reconnect failed for endpoint_id: " << endpoint_id;
<< " Reconnect failed for endpoint_id: " << endpoint_id;
}, },
}; };
@@ -511,7 +511,7 @@ void ServiceControllerRouter::RequestConnectionV3(
client, remote_device, std::move(old_info), connection_options); client, remote_device, std::move(old_info), connection_options);
if (!status.Ok()) { if (!status.Ok()) {
LOG(WARNING) << "Unable to request connection to endpoint " LOG(WARNING) << "Unable to request connection to endpoint "
<< endpoint_id << ": " << status.ToString(); << endpoint_id << ": " << status.ToString();
client->CancelEndpoint(endpoint_id); client->CancelEndpoint(endpoint_id);
} }
callback(status); callback(status);
@@ -697,8 +697,8 @@ void ServiceControllerRouter::StopAllEndpoints(ClientProxy* client,
"scr-stop-all-endpoints", "scr-stop-all-endpoints",
[this, client, callback = std::move(callback)]() mutable { [this, client, callback = std::move(callback)]() mutable {
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " has requested us to stop all endpoints. We will " << " has requested us to stop all endpoints. We will "
"now reset the client."; "now reset the client.";
FinishClientSession(client); FinishClientSession(client);
callback({Status::kSuccess}); callback({Status::kSuccess});
}); });
@@ -711,8 +711,7 @@ void ServiceControllerRouter::SetCustomSavePath(ClientProxy* client,
"scr-set-custom-save-path", [this, client, path = std::string(path), "scr-set-custom-save-path", [this, client, path = std::string(path),
callback = std::move(callback)]() mutable { callback = std::move(callback)]() mutable {
LOG(INFO) << "Client " << client->GetClientId() LOG(INFO) << "Client " << client->GetClientId()
<< " has requested us to set custom save path to " << " has requested us to set custom save path to " << path;
<< path;
GetServiceController()->SetCustomSavePath(client, path); GetServiceController()->SetCustomSavePath(client, path);
callback({Status::kSuccess}); callback({Status::kSuccess});
}); });
@@ -88,34 +88,31 @@ WebrtcBwuHandler::CreateUpgradedEndpointChannel(
if (web_rtc_credentials.has_location_hint()) { if (web_rtc_credentials.has_location_hint()) {
location_hint = web_rtc_credentials.location_hint(); location_hint = web_rtc_credentials.location_hint();
} }
LOG(INFO) LOG(INFO) << "WebRtcBwuHandler is attempting to connect to remote peer "
<< "WebRtcBwuHandler is attempting to connect to remote peer " << peer_id.GetId() << ", location hint "
<< peer_id.GetId() << ", location hint " << location_hint.location();
<< absl::StrCat(location_hint.location());
ErrorOr<mediums::WebRtcSocketWrapper> socket_result = webrtc_.Connect( ErrorOr<mediums::WebRtcSocketWrapper> socket_result = webrtc_.Connect(
service_id, peer_id, location_hint, service_id, peer_id, location_hint,
client->GetCancellationFlag(endpoint_id), client->GetWebRtcNonCellular()); client->GetCancellationFlag(endpoint_id), client->GetWebRtcNonCellular());
if (socket_result.has_error()) { if (socket_result.has_error()) {
LOG(ERROR) << "WebRtcBwuHandler failed to connect to remote peer (" LOG(ERROR) << "WebRtcBwuHandler failed to connect to remote peer ("
<< peer_id.GetId() << ") on endpoint " << endpoint_id << peer_id.GetId() << ") on endpoint " << endpoint_id
<< ", aborting upgrade."; << ", aborting upgrade.";
return {Error(socket_result.error().operation_result_code().value())}; return {Error(socket_result.error().operation_result_code().value())};
} }
LOG(INFO) << "WebRtcBwuHandler successfully connected to remote " LOG(INFO) << "WebRtcBwuHandler successfully connected to remote "
"peer (" "peer ("
<< peer_id.GetId() << ") while upgrading endpoint " << peer_id.GetId() << ") while upgrading endpoint " << endpoint_id;
<< endpoint_id;
// Create a new WebRtcEndpointChannel. // Create a new WebRtcEndpointChannel.
auto channel = std::make_unique<WebRtcEndpointChannel>( auto channel = std::make_unique<WebRtcEndpointChannel>(
service_id, /*channel_name=*/service_id, socket_result.value()); service_id, /*channel_name=*/service_id, socket_result.value());
if (channel == nullptr) { if (channel == nullptr) {
socket_result.value().Close(); socket_result.value().Close();
LOG(ERROR) LOG(ERROR) << "WebRtcBwuHandler failed to create new EndpointChannel for "
<< "WebRtcBwuHandler failed to create new EndpointChannel for " "outgoing socket, aborting upgrade.";
"outgoing socket, aborting upgrade.";
return {Error( return {Error(
OperationResultCode::NEARBY_WEB_RTC_ENDPOINT_CHANNEL_CREATION_FAILURE)}; OperationResultCode::NEARBY_WEB_RTC_ENDPOINT_CHANNEL_CREATION_FAILURE)};
} }
@@ -126,9 +123,8 @@ WebrtcBwuHandler::CreateUpgradedEndpointChannel(
void WebrtcBwuHandler::HandleRevertInitiatorStateForService( void WebrtcBwuHandler::HandleRevertInitiatorStateForService(
const std::string& upgrade_service_id) { const std::string& upgrade_service_id) {
webrtc_.StopAcceptingConnections(upgrade_service_id); webrtc_.StopAcceptingConnections(upgrade_service_id);
LOG(INFO) LOG(INFO) << "WebrtcBwuHandler successfully reverted state for service "
<< "WebrtcBwuHandler successfully reverted state for service " << upgrade_service_id;
<< upgrade_service_id;
} }
// Called by BWU initiator. Set up WebRTC upgraded medium for this endpoint, // Called by BWU initiator. Set up WebRTC upgraded medium for this endpoint,
@@ -148,15 +144,15 @@ ByteArray WebrtcBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
this, client), this, client),
client->GetWebRtcNonCellular())) { client->GetWebRtcNonCellular())) {
LOG(ERROR) << "WebRtcBwuHandler couldn't initiate the WEB_RTC " LOG(ERROR) << "WebRtcBwuHandler couldn't initiate the WEB_RTC "
"upgrade for endpoint " "upgrade for endpoint "
<< endpoint_id << endpoint_id
<< " because it failed to start listening for " << " because it failed to start listening for "
"incoming WebRTC connections."; "incoming WebRTC connections.";
return {}; return {};
} }
LOG(INFO) << "WebRtcBwuHandler successfully started listening for " LOG(INFO) << "WebRtcBwuHandler successfully started listening for "
"incoming WebRTC connections while upgrading endpoint " "incoming WebRTC connections while upgrading endpoint "
<< endpoint_id; << endpoint_id;
} }
return parser::ForBwuWebrtcPathAvailable(self_id.GetId(), location_hint); return parser::ForBwuWebrtcPathAvailable(self_id.GetId(), location_hint);
@@ -84,8 +84,8 @@ ByteArray WifiDirectBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
int freq = wifi_direct_crendential->GetFrequency(); int freq = wifi_direct_crendential->GetFrequency();
LOG(INFO) << "Start WifiDirect GO with SSID: " << ssid LOG(INFO) << "Start WifiDirect GO with SSID: " << ssid
<< ", Password: " << password << ", Port: " << port << ", Password: " << password << ", Port: " << port
<< ", Gateway: " << gateway << ", Frequency: " << freq; << ", Gateway: " << gateway << ", Frequency: " << freq;
bool disabling_encryption = bool disabling_encryption =
(client->GetAdvertisingOptions().strategy == Strategy::kP2pPointToPoint); (client->GetAdvertisingOptions().strategy == Strategy::kP2pPointToPoint);
@@ -100,9 +100,8 @@ void WifiDirectBwuHandler::HandleRevertInitiatorStateForService(
wifi_direct_medium_.StopWifiDirect(); wifi_direct_medium_.StopWifiDirect();
wifi_direct_medium_.DisconnectWifiDirect(); wifi_direct_medium_.DisconnectWifiDirect();
LOG(INFO) LOG(INFO) << "WifiDirectBwuHandler successfully reverted all states for "
<< "WifiDirectBwuHandler successfully reverted all states for " << "upgrade service ID " << upgrade_service_id;
<< "upgrade service ID " << upgrade_service_id;
} }
ErrorOr<std::unique_ptr<EndpointChannel>> ErrorOr<std::unique_ptr<EndpointChannel>>
@@ -123,8 +122,8 @@ WifiDirectBwuHandler::CreateUpgradedEndpointChannel(
const std::string& gateway = upgrade_path_info_credentials.gateway(); const std::string& gateway = upgrade_path_info_credentials.gateway();
LOG(INFO) << "Received WifiDirect credential SSID: " << ssid LOG(INFO) << "Received WifiDirect credential SSID: " << ssid
<< ", Password:" << password << ", Port:" << port << ", Password:" << password << ", Port:" << port
<< ", Gateway:" << gateway; << ", Gateway:" << gateway;
if (!wifi_direct_medium_.ConnectWifiDirect(ssid, password)) { if (!wifi_direct_medium_.ConnectWifiDirect(ssid, password)) {
LOG(ERROR) << "Connect to WifiDiret GO failed"; LOG(ERROR) << "Connect to WifiDiret GO failed";
@@ -147,7 +146,7 @@ WifiDirectBwuHandler::CreateUpgradedEndpointChannel(
// Create a new WifiDirectEndpointChannel. // Create a new WifiDirectEndpointChannel.
return {std::make_unique<WifiDirectEndpointChannel>( return {std::make_unique<WifiDirectEndpointChannel>(
service_id, /*channel_name=*/service_id, socket_result.value())}; service_id, /*channel_name=*/service_id, socket_result.value())};
} }
void WifiDirectBwuHandler::OnIncomingWifiDirectConnection( void WifiDirectBwuHandler::OnIncomingWifiDirectConnection(
@@ -66,31 +66,29 @@ WifiLanBwuHandler::CreateUpgradedEndpointChannel(
std::int32_t port = upgrade_path_info_socket.wifi_port(); std::int32_t port = upgrade_path_info_socket.wifi_port();
VLOG(1) << "WifiLanBwuHandler is attempting to connect to " VLOG(1) << "WifiLanBwuHandler is attempting to connect to "
<< "available WifiLan service (" << ip_address << ":" << port << "available WifiLan service (" << ip_address << ":" << port
<< ") for endpoint " << endpoint_id; << ") for endpoint " << endpoint_id;
ErrorOr<WifiLanSocket> socket_result = wifi_lan_medium_.Connect( ErrorOr<WifiLanSocket> socket_result = wifi_lan_medium_.Connect(
service_id, ip_address, port, client->GetCancellationFlag(endpoint_id)); service_id, ip_address, port, client->GetCancellationFlag(endpoint_id));
if (socket_result.has_error()) { if (socket_result.has_error()) {
LOG(ERROR) LOG(ERROR) << "WifiLanBwuHandler failed to connect to the WifiLan service ("
<< "WifiLanBwuHandler failed to connect to the WifiLan service (" << WifiUtils::GetHumanReadableIpAddress(ip_address) << ":"
<< WifiUtils::GetHumanReadableIpAddress(ip_address) << ":" << port << port << ") for endpoint " << endpoint_id;
<< ") for endpoint " << endpoint_id;
return {Error(socket_result.error().operation_result_code().value())}; return {Error(socket_result.error().operation_result_code().value())};
} }
VLOG(1) VLOG(1) << "WifiLanBwuHandler successfully connected to WifiLan service ("
<< "WifiLanBwuHandler successfully connected to WifiLan service (" << ip_address << ":" << port << ") while upgrading endpoint "
<< ip_address << ":" << port << ") while upgrading endpoint " << endpoint_id;
<< endpoint_id;
// Create a new WifiLanEndpointChannel. // Create a new WifiLanEndpointChannel.
auto channel = std::make_unique<WifiLanEndpointChannel>( auto channel = std::make_unique<WifiLanEndpointChannel>(
service_id, /*channel_name=*/service_id, socket_result.value()); service_id, /*channel_name=*/service_id, socket_result.value());
if (channel == nullptr) { if (channel == nullptr) {
LOG(ERROR) << "WifiLanBwuHandler failed to create WifiLan endpoint " LOG(ERROR) << "WifiLanBwuHandler failed to create WifiLan endpoint "
<< "channel to the WifiLan service (" << ip_address << "channel to the WifiLan service (" << ip_address << ":"
<< ":" << port << ") for endpoint " << endpoint_id; << port << ") for endpoint " << endpoint_id;
socket_result.value().Close(); socket_result.value().Close();
return {Error( return {Error(
OperationResultCode::NEARBY_LAN_ENDPOINT_CHANNEL_CREATION_FAILURE)}; OperationResultCode::NEARBY_LAN_ENDPOINT_CHANNEL_CREATION_FAILURE)};
@@ -130,17 +128,16 @@ ByteArray WifiLanBwuHandler::HandleInitializeUpgradedMediumForEndpoint(
auto ip_address = credential.first; auto ip_address = credential.first;
auto port = credential.second; auto port = credential.second;
if (ip_address.empty()) { if (ip_address.empty()) {
LOG(INFO) LOG(INFO) << "WifiLanBwuHandler couldn't initiate the wifi_lan upgrade for "
<< "WifiLanBwuHandler couldn't initiate the wifi_lan upgrade for " << "service " << upgrade_service_id << " and endpoint "
<< "service " << upgrade_service_id << " and endpoint " << endpoint_id << endpoint_id
<< " because the wifi_lan ip address were unable to be obtained."; << " because the wifi_lan ip address were unable to be obtained.";
return {}; return {};
} }
LOG(INFO) LOG(INFO) << "WifiLanBwuHandler retrieved WIFI_LAN credentials. IP addr: "
<< "WifiLanBwuHandler retrieved WIFI_LAN credentials. IP addr: " << ip_address[0] << "." << ip_address[1] << "." << ip_address[2]
<< ip_address[0] << "." << ip_address[1] << "." << ip_address[2] << "." << "." << ip_address[3] << ", Port: " << port;
<< ip_address[3] << ", Port: " << port;
return parser::ForBwuWifiLanPathAvailable(ip_address, port); return parser::ForBwuWifiLanPathAvailable(ip_address, port);
} }
@@ -149,7 +146,7 @@ void WifiLanBwuHandler::HandleRevertInitiatorStateForService(
const std::string& upgrade_service_id) { const std::string& upgrade_service_id) {
wifi_lan_medium_.StopAcceptingConnections(upgrade_service_id); wifi_lan_medium_.StopAcceptingConnections(upgrade_service_id);
LOG(INFO) << "WifiLanBwuHandler successfully reverted all states for " LOG(INFO) << "WifiLanBwuHandler successfully reverted all states for "
<< "upgrade service ID " << upgrade_service_id; << "upgrade service ID " << upgrade_service_id;
} }
// Accept Connection Callback. // Accept Connection Callback.
@@ -37,15 +37,14 @@ location::nearby::proto::connections::Medium WifiLanEndpointChannel::GetMedium()
void WifiLanEndpointChannel::CloseImpl() { void WifiLanEndpointChannel::CloseImpl() {
auto status = socket_.Close(); auto status = socket_.Close();
if (!status.Ok()) { if (!status.Ok()) {
LOG(INFO) LOG(INFO) << "Failed to close underlying socket for WifiLanEndpointChannel "
<< "Failed to close underlying socket for WifiLanEndpointChannel " << GetName() << " : exception = " << status.value;
<< GetName() << " : exception = " << status.value;
} }
} }
bool WifiLanEndpointChannel::EnableMultiplexSocket() { bool WifiLanEndpointChannel::EnableMultiplexSocket() {
LOG(INFO) << "WifiLanEndpointChannel MultiplexSocket will be " LOG(INFO) << "WifiLanEndpointChannel MultiplexSocket will be "
"enabled if the WifiLan MultiplexSocket is valid"; "enabled if the WifiLan MultiplexSocket is valid";
socket_.EnableMultiplexSocket(); socket_.EnableMultiplexSocket();
return true; return true;
} }
+56 -65
View File
@@ -39,27 +39,26 @@ void NearbyHttpClient::StartRequest(
const HttpRequest& request, const HttpRequest& request,
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)> callback) { absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)> callback) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
executor_.Execute( executor_.Execute([request = std::move(request),
[request = std::move(request), callback = std::move(callback)]() mutable { callback = std::move(callback)]() mutable {
LOG(INFO) << __func__ << ": Start async request to url=" LOG(INFO) << __func__ << ": Start async request to url="
<< request.GetUrl().GetUrlPath(); << request.GetUrl().GetUrlPath();
absl::StatusOr<HttpResponse> response = InternalGetResponse(request); absl::StatusOr<HttpResponse> response = InternalGetResponse(request);
if (response.ok()) { if (response.ok()) {
LOG(INFO) LOG(INFO) << __func__
<< __func__ << ": Got response from url=" << request.GetUrl().GetUrlPath();
<< ": Got response from url=" << request.GetUrl().GetUrlPath(); } else {
} else { LOG(ERROR) << __func__ << ": Failed to get response from url="
LOG(ERROR) << __func__ << ": Failed to get response from url=" << request.GetUrl().GetUrlPath() << ", status"
<< request.GetUrl().GetUrlPath() << ", status" << response.status();
<< response.status(); }
}
if (callback) { if (callback) {
callback(response); callback(response);
} }
LOG(INFO) << __func__ << ": Completed request to url=" LOG(INFO) << __func__
<< request.GetUrl().GetUrlPath(); << ": Completed request to url=" << request.GetUrl().GetUrlPath();
}); });
} }
void NearbyHttpClient::StartCancellableRequest( void NearbyHttpClient::StartCancellableRequest(
@@ -71,63 +70,55 @@ void NearbyHttpClient::StartCancellableRequest(
callback(absl::InvalidArgumentError("invalid cancellable request")); callback(absl::InvalidArgumentError("invalid cancellable request"));
return; return;
} }
executor_ executor_.Execute([cancellable_request = std::move(cancellable_request),
.Execute( callback = std::move(callback)]() mutable {
[cancellable_request = std::move(cancellable_request), LOG(INFO) << __func__ << ": Start async request to url="
callback = std::move(callback)]() mutable { << cancellable_request->http_request().GetUrl().GetUrlPath();
LOG(INFO) if (cancellable_request->is_cancelled()) {
<< __func__ << ": Start async request to url=" LOG(WARNING) << __func__ << ": Async request to url="
<< cancellable_request->http_request().GetUrl().GetUrlPath()
<< " is cancelled.";
return;
}
absl::StatusOr<HttpResponse> response =
InternalGetResponse(cancellable_request->http_request());
if (response.ok()) {
LOG(INFO) << __func__ << ": Got response from url="
<< cancellable_request->http_request().GetUrl().GetUrlPath(); << cancellable_request->http_request().GetUrl().GetUrlPath();
if (cancellable_request->is_cancelled()) { } else {
LOG(WARNING) LOG(ERROR) << __func__ << ": Failed to get response from url="
<< __func__ << ": Async request to url=" << cancellable_request->http_request().GetUrl().GetUrlPath()
<< cancellable_request->http_request().GetUrl().GetUrlPath() << ", status" << response.status();
<< " is cancelled."; }
return;
}
absl::StatusOr<HttpResponse> response =
InternalGetResponse(cancellable_request->http_request());
if (response.ok()) {
LOG(INFO)
<< __func__ << ": Got response from url="
<< cancellable_request->http_request().GetUrl().GetUrlPath();
} else {
LOG(ERROR)
<< __func__ << ": Failed to get response from url="
<< cancellable_request->http_request().GetUrl().GetUrlPath()
<< ", status" << response.status();
}
if (cancellable_request->is_cancelled()) { if (cancellable_request->is_cancelled()) {
LOG(WARNING) LOG(WARNING) << __func__ << ": Async request to url="
<< __func__ << ": Async request to url=" << cancellable_request->http_request().GetUrl().GetUrlPath()
<< cancellable_request->http_request().GetUrl().GetUrlPath() << " is cancelled.";
<< " is cancelled."; return;
return; }
}
if (callback) { if (callback) {
callback(response); callback(response);
} }
LOG(INFO) LOG(INFO) << __func__ << ": Completed request to url="
<< __func__ << ": Completed request to url=" << cancellable_request->http_request().GetUrl().GetUrlPath();
<< cancellable_request->http_request().GetUrl().GetUrlPath(); });
});
} }
absl::StatusOr<HttpResponse> NearbyHttpClient::GetResponse( absl::StatusOr<HttpResponse> NearbyHttpClient::GetResponse(
const HttpRequest& request) { const HttpRequest& request) {
LOG(INFO) << __func__ << ": Start request to url=" LOG(INFO) << __func__
<< request.GetUrl().GetUrlPath(); << ": Start request to url=" << request.GetUrl().GetUrlPath();
absl::StatusOr<HttpResponse> response = InternalGetResponse(request); absl::StatusOr<HttpResponse> response = InternalGetResponse(request);
if (response.ok()) { if (response.ok()) {
LOG(INFO) << __func__ << ": Got response from url=" LOG(INFO) << __func__
<< request.GetUrl().GetUrlPath(); << ": Got response from url=" << request.GetUrl().GetUrlPath();
} else { } else {
LOG(ERROR) << __func__ << ": Failed to get response from url=" LOG(ERROR) << __func__ << ": Failed to get response from url="
<< request.GetUrl().GetUrlPath() << ", status" << request.GetUrl().GetUrlPath() << ", status"
<< response.status(); << response.status();
} }
return response; return response;
+1 -1
View File
@@ -167,7 +167,7 @@ class AwdlServerSocket final {
std::unique_ptr<api::AwdlSocket> socket = impl_->Accept(); std::unique_ptr<api::AwdlSocket> socket = impl_->Accept();
if (!socket) { if (!socket) {
LOG(INFO) << "AwdlServerSocket Accept() failed on server socket: " LOG(INFO) << "AwdlServerSocket Accept() failed on server socket: "
<< this; << this;
} }
return AwdlSocket(std::move(socket)); return AwdlSocket(std::move(socket));
} }
+8 -10
View File
@@ -70,8 +70,8 @@ bool BleMedium::StartScanning(
auto context = peripherals_.find(&peripheral); auto context = peripherals_.find(&peripheral);
if (context == peripherals_.end()) return; if (context == peripherals_.end()) return;
LOG(INFO) << "Removing peripheral=" LOG(INFO) << "Removing peripheral="
<< context->second->peripheral.GetName() << context->second->peripheral.GetName()
<< ", impl=" << &peripheral; << ", impl=" << &peripheral;
discovered_peripheral_callback_.peripheral_lost_cb( discovered_peripheral_callback_.peripheral_lost_cb(
context->second->peripheral, service_id); context->second->peripheral, service_id);
}, },
@@ -103,11 +103,11 @@ bool BleMedium::StartAcceptingConnections(const std::string& service_id,
auto& context = *pair.first->second; auto& context = *pair.first->second;
if (!pair.second) { if (!pair.second) {
LOG(INFO) << "Accepting (again) socket=" << &context.socket LOG(INFO) << "Accepting (again) socket=" << &context.socket
<< ", impl=" << &socket; << ", impl=" << &socket;
} else { } else {
context.socket = BleSocket(&socket); context.socket = BleSocket(&socket);
LOG(INFO) LOG(INFO) << "Accepting socket=" << &context.socket
<< "Accepting socket=" << &context.socket << ", impl=" << &socket; << ", impl=" << &socket;
} }
if (accepted_connection_callback_) { if (accepted_connection_callback_) {
accepted_connection_callback_(context.socket, service_id); accepted_connection_callback_(context.socket, service_id);
@@ -120,8 +120,7 @@ bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
accepted_connection_callback_ = nullptr; accepted_connection_callback_ = nullptr;
sockets_.clear(); sockets_.clear();
LOG(INFO) << "Ble accepted connection disabled: impl=" LOG(INFO) << "Ble accepted connection disabled: impl=" << &GetImpl();
<< &GetImpl();
} }
return impl_->StopAcceptingConnections(service_id); return impl_->StopAcceptingConnections(service_id);
} }
@@ -131,9 +130,8 @@ BleSocket BleMedium::Connect(BlePeripheral& peripheral,
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
{ {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
LOG(INFO) << "BleMedium::Connect: peripheral=" LOG(INFO) << "BleMedium::Connect: peripheral=" << peripheral.GetName()
<< peripheral.GetName() << ",impl=" << &peripheral.GetImpl();
<< ",impl=" << &peripheral.GetImpl();
} }
return BleSocket( return BleSocket(
impl_->Connect(peripheral.GetImpl(), service_id, cancellation_flag)); impl_->Connect(peripheral.GetImpl(), service_id, cancellation_flag));
+8 -10
View File
@@ -78,10 +78,9 @@ TEST_P(BleMediumTest, CanStartAcceptingConnectionsAndConnect) {
BlePeripheral& peripheral, const std::string& service_id, BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes, const ByteArray& advertisement_bytes,
bool fast_advertisement) { bool fast_advertisement) {
LOG(INFO) LOG(INFO) << "Discovered peripheral=" << peripheral.GetName()
<< "Discovered peripheral=" << peripheral.GetName() << ", impl=" << &peripheral.GetImpl()
<< ", impl=" << &peripheral.GetImpl() << ", fast advertisement=" << fast_advertisement;
<< ", fast advertisement=" << fast_advertisement;
discovered_peripheral = &peripheral; discovered_peripheral = &peripheral;
found_latch.CountDown(); found_latch.CountDown();
}, },
@@ -91,7 +90,7 @@ TEST_P(BleMediumTest, CanStartAcceptingConnectionsAndConnect) {
ble_b.StartAcceptingConnections( ble_b.StartAcceptingConnections(
service_id, [&](BleSocket socket, const std::string& service_id) { service_id, [&](BleSocket socket, const std::string& service_id) {
LOG(INFO) << "Connection accepted: socket=" << &socket LOG(INFO) << "Connection accepted: socket=" << &socket
<< ", service_id=" << service_id; << ", service_id=" << service_id;
accepted_latch.CountDown(); accepted_latch.CountDown();
}); });
EXPECT_TRUE(found_latch.Await(kWaitDuration).result()); EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
@@ -136,10 +135,9 @@ TEST_P(BleMediumTest, CanCancelConnect) {
BlePeripheral& peripheral, const std::string& service_id, BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes, const ByteArray& advertisement_bytes,
bool fast_advertisement) { bool fast_advertisement) {
LOG(INFO) LOG(INFO) << "Discovered peripheral=" << peripheral.GetName()
<< "Discovered peripheral=" << peripheral.GetName() << ", impl=" << &peripheral.GetImpl()
<< ", impl=" << &peripheral.GetImpl() << ", fast advertisement=" << fast_advertisement;
<< ", fast advertisement=" << fast_advertisement;
discovered_peripheral = &peripheral; discovered_peripheral = &peripheral;
found_latch.CountDown(); found_latch.CountDown();
}, },
@@ -149,7 +147,7 @@ TEST_P(BleMediumTest, CanCancelConnect) {
ble_b.StartAcceptingConnections( ble_b.StartAcceptingConnections(
service_id, [&](BleSocket socket, const std::string& service_id) { service_id, [&](BleSocket socket, const std::string& service_id) {
LOG(INFO) << "Connection accepted: socket=" << &socket LOG(INFO) << "Connection accepted: socket=" << &socket
<< ", service_id=" << service_id; << ", service_id=" << service_id;
accepted_latch.CountDown(); accepted_latch.CountDown();
}); });
EXPECT_TRUE(found_latch.Await(kWaitDuration).result()); EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+5 -7
View File
@@ -27,9 +27,9 @@ namespace nearby {
BlockingQueueStream::BlockingQueueStream() { BlockingQueueStream::BlockingQueueStream() {
LOG(INFO) << "Create a BlockingQueueStream with size " LOG(INFO) << "Create a BlockingQueueStream with size "
<< FeatureFlags::GetInstance() << FeatureFlags::GetInstance()
.GetFlags() .GetFlags()
.blocking_queue_stream_queue_capacity; .blocking_queue_stream_queue_capacity;
} }
ExceptionOr<ByteArray> BlockingQueueStream::Read(std::int64_t size) { ExceptionOr<ByteArray> BlockingQueueStream::Read(std::int64_t size) {
@@ -39,8 +39,7 @@ ExceptionOr<ByteArray> BlockingQueueStream::Read(std::int64_t size) {
} }
if (is_closed_) { if (is_closed_) {
LOG(INFO) LOG(INFO) << "Failed to read BlockingQueueStream because it was closed.";
<< "Failed to read BlockingQueueStream because it was closed.";
return ExceptionOr<ByteArray>(Exception::kIo); return ExceptionOr<ByteArray>(Exception::kIo);
} }
@@ -67,8 +66,7 @@ void BlockingQueueStream::Write(const ByteArray& bytes) {
return; return;
} }
if (is_closed_) { if (is_closed_) {
LOG(INFO) LOG(INFO) << "Failed to write BlockingQueueStream because it was closed.";
<< "Failed to write BlockingQueueStream because it was closed.";
return; return;
} }
is_writing_ = true; is_writing_ = true;
+1 -2
View File
@@ -600,8 +600,7 @@ TEST_F(BluetoothClassicMediumTest, CancelBluetoothPairing) {
bt_a_->StartDiscovery( bt_a_->StartDiscovery(
DiscoveryCallback{.device_discovered_cb = [&](BluetoothDevice& device) { DiscoveryCallback{.device_discovered_cb = [&](BluetoothDevice& device) {
LOG(INFO) << "Device discovered: " << device.GetName(); LOG(INFO) << "Device discovered: " << device.GetName();
LOG(INFO) << "Device discovered address: " LOG(INFO) << "Device discovered address: " << device.GetMacAddress();
<< device.GetMacAddress();
EXPECT_EQ(device.GetName(), adapter_b_->GetName()); EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device; discovered_device = &device;
found_latch.CountDown(); found_latch.CountDown();
+22 -26
View File
@@ -65,8 +65,7 @@ bool BleServerSocket::Connect(BleSocket& socket) {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (closed_) return false; if (closed_) return false;
if (socket.IsConnected()) { if (socket.IsConnected()) {
LOG(ERROR) LOG(ERROR) << "Failed to connect to Ble server socket: already connected";
<< "Failed to connect to Ble server socket: already connected";
return true; // already connected. return true; // already connected.
} }
// add client socket to the pending list // add client socket to the pending list
@@ -128,7 +127,7 @@ BleMedium::~BleMedium() {
accept_loops_runner_.Shutdown(); accept_loops_runner_.Shutdown();
LOG(INFO) << "BleMedium dtor advertising_accept_thread_running_ = " LOG(INFO) << "BleMedium dtor advertising_accept_thread_running_ = "
<< acceptance_thread_running_.load(); << acceptance_thread_running_.load();
// If acceptance thread is still running, wait to finish. // If acceptance thread is still running, wait to finish.
if (acceptance_thread_running_) { if (acceptance_thread_running_) {
while (acceptance_thread_running_) { while (acceptance_thread_running_) {
@@ -143,11 +142,11 @@ bool BleMedium::StartAdvertising(
const std::string& service_id, const ByteArray& advertisement_bytes, const std::string& service_id, const ByteArray& advertisement_bytes,
const std::string& fast_advertisement_service_uuid) { const std::string& fast_advertisement_service_uuid) {
LOG(INFO) << "G3 Ble StartAdvertising: service_id=" << service_id LOG(INFO) << "G3 Ble StartAdvertising: service_id=" << service_id
<< ", advertisement bytes=" << ", advertisement bytes="
<< absl::BytesToHexString(std::string(advertisement_bytes)) << absl::BytesToHexString(std::string(advertisement_bytes)) << "("
<< "(" << advertisement_bytes.size() << ")," << advertisement_bytes.size() << "),"
<< ", fast advertisement service uuid=" << ", fast advertisement service uuid="
<< absl::BytesToHexString(fast_advertisement_service_uuid); << absl::BytesToHexString(fast_advertisement_service_uuid);
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
auto& peripheral = adapter_->GetPeripheral(); auto& peripheral = adapter_->GetPeripheral();
peripheral.SetAdvertisementBytes(service_id, advertisement_bytes); peripheral.SetAdvertisementBytes(service_id, advertisement_bytes);
@@ -181,7 +180,7 @@ bool BleMedium::StopAdvertising(const std::string& service_id) {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (advertising_info_.Empty()) { if (advertising_info_.Empty()) {
LOG(INFO) << "G3 Ble StopAdvertising: Can't stop advertising " LOG(INFO) << "G3 Ble StopAdvertising: Can't stop advertising "
"because we never started advertising."; "because we never started advertising.";
return false; return false;
} }
advertising_info_.Clear(); advertising_info_.Clear();
@@ -194,8 +193,8 @@ bool BleMedium::StopAdvertising(const std::string& service_id) {
accept_loops_runner_.Shutdown(); accept_loops_runner_.Shutdown();
if (server_socket_ == nullptr) { if (server_socket_ == nullptr) {
LOG(ERROR) << "G3 Ble StopAdvertising: Failed to find Ble Server " LOG(ERROR) << "G3 Ble StopAdvertising: Failed to find Ble Server "
"socket: service_id=" "socket: service_id="
<< service_id; << service_id;
// Fall through for server socket not found. // Fall through for server socket not found.
return true; return true;
} }
@@ -231,7 +230,7 @@ bool BleMedium::StopScanning(const std::string& service_id) {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (scanning_info_.Empty()) { if (scanning_info_.Empty()) {
LOG(INFO) << "G3 Ble StopDiscovery: Can't stop scanning because " LOG(INFO) << "G3 Ble StopDiscovery: Can't stop scanning because "
"we never started scanning."; "we never started scanning.";
return false; return false;
} }
scanning_info_.Clear(); scanning_info_.Clear();
@@ -244,8 +243,7 @@ bool BleMedium::StopScanning(const std::string& service_id) {
bool BleMedium::StartAcceptingConnections(const std::string& service_id, bool BleMedium::StartAcceptingConnections(const std::string& service_id,
AcceptedConnectionCallback callback) { AcceptedConnectionCallback callback) {
LOG(INFO) << "G3 Ble StartAcceptingConnections: service_id=" LOG(INFO) << "G3 Ble StartAcceptingConnections: service_id=" << service_id;
<< service_id;
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
env.UpdateBleMediumForAcceptedConnection(*this, service_id, env.UpdateBleMediumForAcceptedConnection(*this, service_id,
std::move(callback)); std::move(callback));
@@ -253,8 +251,7 @@ bool BleMedium::StartAcceptingConnections(const std::string& service_id,
} }
bool BleMedium::StopAcceptingConnections(const std::string& service_id) { bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
LOG(INFO) << "G3 Ble StopAcceptingConnections: service_id=" LOG(INFO) << "G3 Ble StopAcceptingConnections: service_id=" << service_id;
<< service_id;
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
env.UpdateBleMediumForAcceptedConnection(*this, service_id, {}); env.UpdateBleMediumForAcceptedConnection(*this, service_id, {});
return true; return true;
@@ -264,9 +261,9 @@ std::unique_ptr<api::BleSocket> BleMedium::Connect(
api::BlePeripheral& remote_peripheral, const std::string& service_id, api::BlePeripheral& remote_peripheral, const std::string& service_id,
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
LOG(INFO) << "G3 Ble Connect [self]: medium=" << this LOG(INFO) << "G3 Ble Connect [self]: medium=" << this
<< ", adapter=" << &GetAdapter() << ", adapter=" << &GetAdapter()
<< ", peripheral=" << &GetAdapter().GetPeripheral() << ", peripheral=" << &GetAdapter().GetPeripheral()
<< ", service_id=" << service_id; << ", service_id=" << service_id;
// First, find an instance of remote medium, that exposed this peripheral. // First, find an instance of remote medium, that exposed this peripheral.
auto& adapter = static_cast<BlePeripheral&>(remote_peripheral).GetAdapter(); auto& adapter = static_cast<BlePeripheral&>(remote_peripheral).GetAdapter();
auto* medium = static_cast<BleMedium*>(adapter.GetBleMedium()); auto* medium = static_cast<BleMedium*>(adapter.GetBleMedium());
@@ -275,9 +272,8 @@ std::unique_ptr<api::BleSocket> BleMedium::Connect(
BleServerSocket* remote_server_socket = nullptr; BleServerSocket* remote_server_socket = nullptr;
LOG(INFO) << "G3 Ble Connect [peer]: medium=" << medium LOG(INFO) << "G3 Ble Connect [peer]: medium=" << medium
<< ", adapter=" << &adapter << ", adapter=" << &adapter << ", peripheral=" << &remote_peripheral
<< ", peripheral=" << &remote_peripheral << ", service_id=" << service_id;
<< ", service_id=" << service_id;
// Then, find our server socket context in this medium. // Then, find our server socket context in this medium.
{ {
absl::MutexLock medium_lock(&medium->mutex_); absl::MutexLock medium_lock(&medium->mutex_);
@@ -292,8 +288,8 @@ std::unique_ptr<api::BleSocket> BleMedium::Connect(
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(ERROR) << "G3 BLE Connect: Has been cancelled: " LOG(ERROR) << "G3 BLE Connect: Has been cancelled: "
"service_id=" "service_id="
<< service_id; << service_id;
return {}; return {};
} }
@@ -307,8 +303,8 @@ std::unique_ptr<api::BleSocket> BleMedium::Connect(
// Finally, Request to connect to this socket. // Finally, Request to connect to this socket.
if (!remote_server_socket->Connect(*socket)) { if (!remote_server_socket->Connect(*socket)) {
LOG(ERROR) << "G3 Ble Connect: Failed to connect to existing Ble " LOG(ERROR) << "G3 Ble Connect: Failed to connect to existing Ble "
"Server socket: service_id=" "Server socket: service_id="
<< service_id; << service_id;
return {}; return {};
} }
@@ -65,8 +65,7 @@ bool BluetoothServerSocket::Connect(BluetoothSocket& socket) {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (closed_) return false; if (closed_) return false;
if (socket.IsConnected()) { if (socket.IsConnected()) {
LOG(ERROR) LOG(ERROR) << "Failed to connect to BT server socket: already connected";
<< "Failed to connect to BT server socket: already connected";
return true; // already connected. return true; // already connected.
} }
// add client socket to the pending list // add client socket to the pending list
@@ -172,8 +171,8 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
api::BluetoothDevice& remote_device, const std::string& service_uuid, api::BluetoothDevice& remote_device, const std::string& service_uuid,
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
LOG(INFO) << "G3 ConnectToService [self]: medium=" << this LOG(INFO) << "G3 ConnectToService [self]: medium=" << this
<< ", adapter=" << &GetAdapter() << ", adapter=" << &GetAdapter()
<< ", device=" << &GetAdapter().GetDevice(); << ", device=" << &GetAdapter().GetDevice();
// First, find an instance of remote medium, that exposed this device. // First, find an instance of remote medium, that exposed this device.
auto& adapter = static_cast<BluetoothDevice&>(remote_device).GetAdapter(); auto& adapter = static_cast<BluetoothDevice&>(remote_device).GetAdapter();
auto* medium = auto* medium =
@@ -183,24 +182,23 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
BluetoothServerSocket* server_socket = nullptr; BluetoothServerSocket* server_socket = nullptr;
LOG(INFO) << "G3 ConnectToService [peer]: medium=" << medium LOG(INFO) << "G3 ConnectToService [peer]: medium=" << medium
<< ", adapter=" << &adapter << ", device=" << &remote_device << ", adapter=" << &adapter << ", device=" << &remote_device
<< ", uuid=" << service_uuid.c_str(); << ", uuid=" << service_uuid;
// Then, find our server socket context in this medium. // Then, find our server socket context in this medium.
{ {
absl::MutexLock medium_lock(&medium->mutex_); absl::MutexLock medium_lock(&medium->mutex_);
auto item = medium->sockets_.find(service_uuid); auto item = medium->sockets_.find(service_uuid);
server_socket = item != medium->sockets_.end() ? item->second : nullptr; server_socket = item != medium->sockets_.end() ? item->second : nullptr;
if (server_socket == nullptr) { if (server_socket == nullptr) {
LOG(ERROR) << "Failed to find BT Server socket: uuid=" LOG(ERROR) << "Failed to find BT Server socket: uuid=" << service_uuid;
<< service_uuid;
return {}; return {};
} }
} }
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(ERROR) << "G3 Bluetooth Connect: Has been cancelled: " LOG(ERROR) << "G3 Bluetooth Connect: Has been cancelled: "
"service_uuid=" "service_uuid="
<< service_uuid; << service_uuid;
return {}; return {};
} }
@@ -212,23 +210,20 @@ std::unique_ptr<api::BluetoothSocket> BluetoothClassicMedium::ConnectToService(
auto socket = std::make_unique<BluetoothSocket>(&GetAdapter()); auto socket = std::make_unique<BluetoothSocket>(&GetAdapter());
// Finally, Request to connect to this socket. // Finally, Request to connect to this socket.
if (!server_socket->Connect(*socket)) { if (!server_socket->Connect(*socket)) {
LOG(ERROR) LOG(ERROR) << "Failed to connect to existing BT Server socket: uuid="
<< "Failed to connect to existing BT Server socket: uuid=" << service_uuid;
<< service_uuid;
return {}; return {};
} }
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(ERROR) LOG(ERROR) << "G3 Bluetooth Connect: Has been cancelled after connected: "
<< "G3 Bluetooth Connect: Has been cancelled after connected: " "service_uuid="
"service_uuid=" << service_uuid;
<< service_uuid;
socket->Close(); socket->Close();
return {}; return {};
} }
LOG(INFO) << "G3 ConnectToService: connected: socket=" LOG(INFO) << "G3 ConnectToService: connected: socket=" << socket.get();
<< socket.get();
return socket; return socket;
} }
@@ -240,8 +235,7 @@ BluetoothClassicMedium::ListenForService(const std::string& service_name,
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
sockets_.erase(uuid); sockets_.erase(uuid);
}); });
LOG(INFO) << "Adding service: medium=" << this LOG(INFO) << "Adding service: medium=" << this << ", uuid=" << service_uuid;
<< ", uuid=" << service_uuid;
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
sockets_.emplace(service_uuid, socket.get()); sockets_.emplace(service_uuid, socket.get());
return socket; return socket;
@@ -64,24 +64,20 @@ void CredentialStorageImpl::SaveCredentials(
} }
if (private_credentials.empty()) { if (private_credentials.empty()) {
LOG(INFO) << "There are no Private Credentials for account: [" LOG(INFO) << "There are no Private Credentials for account: ["
<< account_name << "], manager app ID:[" << manager_app_id << account_name << "], manager app ID:[" << manager_app_id << "]";
<< "]";
} else { } else {
LOG(INFO) << "G3 Save Private Credentials for account: [" LOG(INFO) << "G3 Save Private Credentials for account: [" << account_name
<< account_name << "], manager app ID:[" << manager_app_id << "], manager app ID:[" << manager_app_id << "]";
<< "]";
SaveLocalCredentialsLocked(manager_app_id, account_name, SaveLocalCredentialsLocked(manager_app_id, account_name,
private_credentials); private_credentials);
} }
if (public_credentials.empty()) { if (public_credentials.empty()) {
LOG(INFO) << "There are no Public Credentials for account: [" LOG(INFO) << "There are no Public Credentials for account: ["
<< account_name << "], manager app ID:[" << manager_app_id << account_name << "], manager app ID:[" << manager_app_id << "]";
<< "]";
} else { } else {
LOG(INFO) << "G3 Save Public Credentials for account: [" LOG(INFO) << "G3 Save Public Credentials for account: [" << account_name
<< account_name << "], manager app ID:[" << manager_app_id << "], manager app ID:[" << manager_app_id << "]";
<< "]";
PublicCredentialKey key = CreatePublicCredentialKey( PublicCredentialKey key = CreatePublicCredentialKey(
manager_app_id, account_name, public_credential_type); manager_app_id, account_name, public_credential_type);
auto public_result = auto public_result =
@@ -111,9 +107,8 @@ void CredentialStorageImpl::SaveLocalCredentialsLocked(
void CredentialStorageImpl::UpdateLocalCredential( void CredentialStorageImpl::UpdateLocalCredential(
absl::string_view manager_app_id, absl::string_view account_name, absl::string_view manager_app_id, absl::string_view account_name,
LocalCredential credential, SaveCredentialsResultCallback callback) { LocalCredential credential, SaveCredentialsResultCallback callback) {
LOG(INFO) << "G3 Update Private Credential for for account: [" LOG(INFO) << "G3 Update Private Credential for for account: [" << account_name
<< account_name << "], manager app ID:[" << manager_app_id << "], manager app ID:[" << manager_app_id << "]";
<< "]";
absl::StatusOr<std::vector<LocalCredential>> credentials = absl::StatusOr<std::vector<LocalCredential>> credentials =
GetLocalCredentialsLocked(CredentialSelector{ GetLocalCredentialsLocked(CredentialSelector{
.manager_app_id = std::string(manager_app_id), .manager_app_id = std::string(manager_app_id),
@@ -150,7 +145,7 @@ CredentialStorageImpl::GetLocalCredentialsLocked(
credential_selector.manager_app_id, credential_selector.account_name); credential_selector.manager_app_id, credential_selector.account_name);
if (private_credentials_map_.find(key) == private_credentials_map_.end()) { if (private_credentials_map_.find(key) == private_credentials_map_.end()) {
LOG(WARNING) << "There are no Private Credentials stored for key:" LOG(WARNING) << "There are no Private Credentials stored for key:"
<< std::get<0>(key) << ", " << std::get<1>(key); << std::get<0>(key) << ", " << std::get<1>(key);
return absl::NotFoundError( return absl::NotFoundError(
absl::StrFormat("No private credentials for %v", credential_selector)); absl::StrFormat("No private credentials for %v", credential_selector));
} }
@@ -174,8 +169,8 @@ void CredentialStorageImpl::GetPublicCredentials(
public_credential_type); public_credential_type);
if (public_credentials_map_.find(key) == public_credentials_map_.end()) { if (public_credentials_map_.find(key) == public_credentials_map_.end()) {
LOG(WARNING) << "There are no Public Credentials stored for key:" LOG(WARNING) << "There are no Public Credentials stored for key:"
<< std::get<0>(key) << ", " << std::get<1>(key) << ", " << std::get<0>(key) << ", " << std::get<1>(key) << ", "
<< std::get<2>(key); << std::get<2>(key);
std::move(callback.credentials_fetched_cb)(absl::NotFoundError( std::move(callback.credentials_fetched_cb)(absl::NotFoundError(
absl::StrFormat("No public credentials for %v", credential_selector))); absl::StrFormat("No public credentials for %v", credential_selector)));
return; return;
@@ -131,7 +131,7 @@ bool WifiDirectMedium::StartWifiDirect(
wifi_direct_credentials->SetPassword(password); wifi_direct_credentials->SetPassword(password);
LOG(INFO) << "G3 StartWifiDirect GO: ssid=" << ssid LOG(INFO) << "G3 StartWifiDirect GO: ssid=" << ssid
<< ", password:" << password; << ", password:" << password;
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
env.UpdateWifiDirectMediumForStartOrConnect(*this, wifi_direct_credentials, env.UpdateWifiDirectMediumForStartOrConnect(*this, wifi_direct_credentials,
@@ -156,8 +156,8 @@ bool WifiDirectMedium::ConnectWifiDirect(
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
LOG(INFO) << "G3 ConnectWifiDirect : ssid=" LOG(INFO) << "G3 ConnectWifiDirect : ssid="
<< wifi_direct_credentials->GetSSID() << wifi_direct_credentials->GetSSID()
<< ", password:" << wifi_direct_credentials->GetPassword(); << ", password:" << wifi_direct_credentials->GetPassword();
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
auto* remote_medium = static_cast<WifiDirectMedium*>( auto* remote_medium = static_cast<WifiDirectMedium*>(
@@ -192,7 +192,7 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
std::string socket_name = WifiDirectServerSocket::GetName(ip_address, port); std::string socket_name = WifiDirectServerSocket::GetName(ip_address, port);
LOG(INFO) << "G3 WifiDirect ConnectToService [self]: medium=" << this LOG(INFO) << "G3 WifiDirect ConnectToService [self]: medium=" << this
<< ", ip address + port=" << socket_name; << ", ip address + port=" << socket_name;
// First, find an instance of remote medium, that exposed this service. // First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
auto* remote_medium = auto* remote_medium =
@@ -202,9 +202,8 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
} }
WifiDirectServerSocket* server_socket = nullptr; WifiDirectServerSocket* server_socket = nullptr;
LOG(INFO) << "G3 WifiDirect ConnectToService [peer]: medium=" LOG(INFO) << "G3 WifiDirect ConnectToService [peer]: medium=" << remote_medium
<< remote_medium << ", remote ip address + port=" << socket_name;
<< ", remote ip address + port=" << socket_name;
// Then, find our server socket context in this medium. // Then, find our server socket context in this medium.
{ {
absl::MutexLock medium_lock(&remote_medium->mutex_); absl::MutexLock medium_lock(&remote_medium->mutex_);
@@ -213,16 +212,15 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
item != remote_medium->server_sockets_.end() ? item->second : nullptr; item != remote_medium->server_sockets_.end() ? item->second : nullptr;
if (server_socket == nullptr) { if (server_socket == nullptr) {
LOG(ERROR) << "G3 WifiDirect Failed to find WifiDirect Server " LOG(ERROR) << "G3 WifiDirect Failed to find WifiDirect Server "
"socket: socket_name=" "socket: socket_name="
<< socket_name; << socket_name;
return nullptr; return nullptr;
} }
} }
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(ERROR) LOG(ERROR) << "G3 WifiDirect Connect: Has been cancelled: socket_name="
<< "G3 WifiDirect Connect: Has been cancelled: socket_name=" << socket_name;
<< socket_name;
return nullptr; return nullptr;
} }
@@ -231,7 +229,7 @@ std::unique_ptr<api::WifiDirectSocket> WifiDirectMedium::ConnectToService(
server_socket->Connect(*socket); server_socket->Connect(*socket);
LOG(INFO) << "G3 WifiDirect GC ConnectToService: connected: socket=" LOG(INFO) << "G3 WifiDirect GC ConnectToService: connected: socket="
<< socket.get(); << socket.get();
return socket; return socket;
} }
@@ -257,7 +255,7 @@ std::unique_ptr<api::WifiDirectServerSocket> WifiDirectMedium::ListenForService(
server_sockets_.erase(socket_name); server_sockets_.erase(socket_name);
}); });
LOG(INFO) << "G3 WifiDirect GO Adding server socket: medium=" << this LOG(INFO) << "G3 WifiDirect GO Adding server socket: medium=" << this
<< ", socket_name=" << socket_name; << ", socket_name=" << socket_name;
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
server_sockets_.insert({socket_name, server_socket.get()}); server_sockets_.insert({socket_name, server_socket.get()});
return server_socket; return server_socket;
@@ -134,7 +134,7 @@ bool WifiHotspotMedium::StartWifiHotspot(
hotspot_credentials->SetPassword(password); hotspot_credentials->SetPassword(password);
LOG(INFO) << "G3 StartWifiHotspot: ssid=" << ssid LOG(INFO) << "G3 StartWifiHotspot: ssid=" << ssid
<< ", password:" << password; << ", password:" << password;
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials, env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials,
@@ -161,9 +161,8 @@ bool WifiHotspotMedium::ConnectWifiHotspot(
HotspotCredentials* hotspot_credentials) { HotspotCredentials* hotspot_credentials) {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
LOG(INFO) << "G3 ConnectWifiHotspot: ssid=" LOG(INFO) << "G3 ConnectWifiHotspot: ssid=" << hotspot_credentials->GetSSID()
<< hotspot_credentials->GetSSID() << ", password:" << hotspot_credentials->GetPassword();
<< ", password:" << hotspot_credentials->GetPassword();
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
auto* remote_medium = static_cast<WifiHotspotMedium*>( auto* remote_medium = static_cast<WifiHotspotMedium*>(
@@ -198,7 +197,7 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
std::string socket_name = WifiHotspotServerSocket::GetName(ip_address, port); std::string socket_name = WifiHotspotServerSocket::GetName(ip_address, port);
LOG(INFO) << "G3 WifiHotspot ConnectToService [self]: medium=" << this LOG(INFO) << "G3 WifiHotspot ConnectToService [self]: medium=" << this
<< ", ip address + port=" << socket_name; << ", ip address + port=" << socket_name;
// First, find an instance of remote medium, that exposed this service. // First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
auto* remote_medium = auto* remote_medium =
@@ -209,8 +208,7 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
WifiHotspotServerSocket* server_socket = nullptr; WifiHotspotServerSocket* server_socket = nullptr;
LOG(INFO) << "G3 WifiHotspot ConnectToService [peer]: medium=" LOG(INFO) << "G3 WifiHotspot ConnectToService [peer]: medium="
<< remote_medium << remote_medium << ", remote ip address + port=" << socket_name;
<< ", remote ip address + port=" << socket_name;
// Then, find our server socket context in this medium. // Then, find our server socket context in this medium.
{ {
absl::MutexLock medium_lock(&remote_medium->mutex_); absl::MutexLock medium_lock(&remote_medium->mutex_);
@@ -219,16 +217,15 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
item != remote_medium->server_sockets_.end() ? item->second : nullptr; item != remote_medium->server_sockets_.end() ? item->second : nullptr;
if (server_socket == nullptr) { if (server_socket == nullptr) {
LOG(ERROR) << "G3 WifiHotspot Failed to find WifiHotspot Server " LOG(ERROR) << "G3 WifiHotspot Failed to find WifiHotspot Server "
"socket: socket_name=" "socket: socket_name="
<< socket_name; << socket_name;
return {}; return {};
} }
} }
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(ERROR) LOG(ERROR) << "G3 WifiHotspot Connect: Has been cancelled: socket_name="
<< "G3 WifiHotspot Connect: Has been cancelled: socket_name=" << socket_name;
<< socket_name;
return {}; return {};
} }
@@ -242,14 +239,13 @@ std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService(
auto socket = std::make_unique<WifiHotspotSocket>(); auto socket = std::make_unique<WifiHotspotSocket>();
// Finally, Request to connect to this socket. // Finally, Request to connect to this socket.
if (!server_socket->Connect(*socket)) { if (!server_socket->Connect(*socket)) {
LOG(ERROR) LOG(ERROR) << "G3 WifiHotspot Failed to connect to existing WifiHotspot "
<< "G3 WifiHotspot Failed to connect to existing WifiHotspot " "Server socket: name="
"Server socket: name=" << socket_name;
<< socket_name;
return {}; return {};
} }
LOG(INFO) << "G3 WifiHotspot ConnectToService: connected: socket=" LOG(INFO) << "G3 WifiHotspot ConnectToService: connected: socket="
<< socket.get(); << socket.get();
return socket; return socket;
} }
@@ -276,7 +272,7 @@ WifiHotspotMedium::ListenForService(int port) {
server_sockets_.erase(socket_name); server_sockets_.erase(socket_name);
}); });
LOG(INFO) << "G3 WifiHotspot Adding server socket: medium=" << this LOG(INFO) << "G3 WifiHotspot Adding server socket: medium=" << this
<< ", socket_name=" << socket_name; << ", socket_name=" << socket_name;
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
server_sockets_.insert({socket_name, server_socket.get()}); server_sockets_.insert({socket_name, server_socket.get()});
return server_socket; return server_socket;
+23 -28
View File
@@ -130,9 +130,9 @@ WifiLanMedium::~WifiLanMedium() {
bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) { bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
std::string service_type = nsd_service_info.GetServiceType(); std::string service_type = nsd_service_info.GetServiceType();
LOG(INFO) << "G3 WifiLan StartAdvertising: nsd_service_info=" LOG(INFO) << "G3 WifiLan StartAdvertising: nsd_service_info="
<< &nsd_service_info << &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName() << ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_type=" << service_type; << ", service_type=" << service_type;
{ {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (advertising_info_.Existed(service_type)) { if (advertising_info_.Existed(service_type)) {
@@ -156,16 +156,15 @@ bool WifiLanMedium::StartAdvertising(const NsdServiceInfo& nsd_service_info) {
bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) { bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
std::string service_type = nsd_service_info.GetServiceType(); std::string service_type = nsd_service_info.GetServiceType();
LOG(INFO) << "G3 WifiLan StopAdvertising: nsd_service_info=" LOG(INFO) << "G3 WifiLan StopAdvertising: nsd_service_info="
<< &nsd_service_info << &nsd_service_info
<< ", service_name=" << nsd_service_info.GetServiceName() << ", service_name=" << nsd_service_info.GetServiceName()
<< ", service_type=" << service_type; << ", service_type=" << service_type;
{ {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (!advertising_info_.Existed(service_type)) { if (!advertising_info_.Existed(service_type)) {
LOG(INFO) LOG(INFO) << "G3 WifiLan StopAdvertising: Can't stop advertising because "
<< "G3 WifiLan StopAdvertising: Can't stop advertising because " "we never started advertising for service_type="
"we never started advertising for service_type=" << service_type;
<< service_type;
return false; return false;
} }
advertising_info_.Remove(service_type); advertising_info_.Remove(service_type);
@@ -178,15 +177,13 @@ bool WifiLanMedium::StopAdvertising(const NsdServiceInfo& nsd_service_info) {
bool WifiLanMedium::StartDiscovery(const std::string& service_type, bool WifiLanMedium::StartDiscovery(const std::string& service_type,
DiscoveredServiceCallback callback) { DiscoveredServiceCallback callback) {
LOG(INFO) << "G3 WifiLan StartDiscovery: service_type=" LOG(INFO) << "G3 WifiLan StartDiscovery: service_type=" << service_type;
<< service_type;
{ {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (discovering_info_.Existed(service_type)) { if (discovering_info_.Existed(service_type)) {
LOG(INFO) LOG(INFO) << "G3 WifiLan StartDiscovery: Can't start discovery because "
<< "G3 WifiLan StartDiscovery: Can't start discovery because " "service_type="
"service_type=" << service_type << " has started already.";
<< service_type << " has started already.";
return false; return false;
} }
} }
@@ -201,8 +198,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_type,
} }
bool WifiLanMedium::StopDiscovery(const std::string& service_type) { bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
LOG(INFO) << "G3 WifiLan StopDiscovery: service_type=" LOG(INFO) << "G3 WifiLan StopDiscovery: service_type=" << service_type;
<< service_type;
{ {
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
if (!discovering_info_.Existed(service_type)) { if (!discovering_info_.Existed(service_type)) {
@@ -223,7 +219,7 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
std::string service_type = remote_service_info.GetServiceType(); std::string service_type = remote_service_info.GetServiceType();
LOG(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this LOG(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", service_type=" << service_type; << ", service_type=" << service_type;
return ConnectToService(remote_service_info.GetIPAddress(), return ConnectToService(remote_service_info.GetIPAddress(),
remote_service_info.GetPort(), cancellation_flag); remote_service_info.GetPort(), cancellation_flag);
} }
@@ -233,7 +229,7 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
std::string socket_name = WifiLanServerSocket::GetName(ip_address, port); std::string socket_name = WifiLanServerSocket::GetName(ip_address, port);
LOG(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this LOG(INFO) << "G3 WifiLan ConnectToService [self]: medium=" << this
<< ", ip address + port=" << socket_name; << ", ip address + port=" << socket_name;
// First, find an instance of remote medium, that exposed this service. // First, find an instance of remote medium, that exposed this service.
auto& env = MediumEnvironment::Instance(); auto& env = MediumEnvironment::Instance();
auto* remote_medium = auto* remote_medium =
@@ -243,9 +239,8 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
} }
WifiLanServerSocket* server_socket = nullptr; WifiLanServerSocket* server_socket = nullptr;
LOG(INFO) << "G3 WifiLan ConnectToService [peer]: medium=" LOG(INFO) << "G3 WifiLan ConnectToService [peer]: medium=" << remote_medium
<< remote_medium << ", remote ip address + port=" << socket_name;
<< ", remote ip address + port=" << socket_name;
// Then, find our server socket context in this medium. // Then, find our server socket context in this medium.
{ {
absl::MutexLock medium_lock(&remote_medium->mutex_); absl::MutexLock medium_lock(&remote_medium->mutex_);
@@ -262,7 +257,7 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
if (cancellation_flag->Cancelled()) { if (cancellation_flag->Cancelled()) {
LOG(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name=" LOG(ERROR) << "G3 WifiLan Connect: Has been cancelled: socket_name="
<< socket_name; << socket_name;
return {}; return {};
} }
@@ -277,12 +272,12 @@ std::unique_ptr<api::WifiLanSocket> WifiLanMedium::ConnectToService(
// Finally, Request to connect to this socket. // Finally, Request to connect to this socket.
if (!server_socket->Connect(*socket)) { if (!server_socket->Connect(*socket)) {
LOG(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan " LOG(ERROR) << "G3 WifiLan Failed to connect to existing WifiLan "
"Server socket: name=" "Server socket: name="
<< socket_name; << socket_name;
return {}; return {};
} }
LOG(INFO) << "G3 WifiLan ConnectToService: connected: socket=" LOG(INFO) << "G3 WifiLan ConnectToService: connected: socket="
<< socket.get(); << socket.get();
return socket; return socket;
} }
@@ -299,7 +294,7 @@ std::unique_ptr<api::WifiLanServerSocket> WifiLanMedium::ListenForService(
server_sockets_.erase(socket_name); server_sockets_.erase(socket_name);
}); });
LOG(INFO) << "G3 WifiLan Adding server socket: medium=" << this LOG(INFO) << "G3 WifiLan Adding server socket: medium=" << this
<< ", socket_name=" << socket_name; << ", socket_name=" << socket_name;
absl::MutexLock lock(&mutex_); absl::MutexLock lock(&mutex_);
server_sockets_.insert({socket_name, server_socket.get()}); server_sockets_.insert({socket_name, server_socket.get()});
return server_socket; return server_socket;
@@ -123,7 +123,7 @@ bool WifiLanMdns::StartMdnsService(
if (status != DNS_REQUEST_PENDING) { if (status != DNS_REQUEST_PENDING) {
LOG(ERROR) << "Failed to start mDNS advertising for service type =" LOG(ERROR) << "Failed to start mDNS advertising for service type ="
<< service_type; << service_type;
return false; return false;
} }
+1 -2
View File
@@ -1302,8 +1302,7 @@ void MediumEnvironment::UnregisterGattServer(api::ble_v2::BleMedium& medium) {
} }
auto& context = it->second; auto& context = it->second;
LOG(INFO) << "Unregistered GattServer for peripheral id:" LOG(INFO) << "Unregistered GattServer for peripheral id:"
<< context.ble_peripheral_id << context.ble_peripheral_id << " on medium:" << &medium;
<< " on medium:" << &medium;
context.gatt_server = nullptr; context.gatt_server = nullptr;
context.ble_peripheral_id = 0LL; context.ble_peripheral_id = 0LL;
latch.CountDown(); latch.CountDown();
+6 -4
View File
@@ -14,6 +14,8 @@
#include "internal/platform/pending_job_registry.h" #include "internal/platform/pending_job_registry.h"
#include "absl/time/time.h"
#include "internal/platform/implementation/system_clock.h"
#include "internal/platform/logging.h" #include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h" #include "internal/platform/mutex_lock.h"
#include "internal/platform/system_clock.h" #include "internal/platform/system_clock.h"
@@ -68,14 +70,14 @@ void PendingJobRegistry::ListJobs() {
auto age = current_time - job.second; auto age = current_time - job.second;
if (age >= kReportPendingJobsOlderThan) { if (age >= kReportPendingJobsOlderThan) {
LOG(INFO) << "Task \"" << job.first << "\" is waiting for " LOG(INFO) << "Task \"" << job.first << "\" is waiting for "
<< absl::ToInt64Seconds(age) << " s"; << absl::ToInt64Seconds(age) << " s";
} }
} }
for (auto& job : running_jobs_) { for (auto& job : running_jobs_) {
auto age = current_time - job.second; auto age = current_time - job.second;
if (age >= kReportRunningJobsOlderThan) { if (age >= kReportRunningJobsOlderThan) {
LOG(INFO) << "Task \"" << job.first << "\" is running for " LOG(INFO) << "Task \"" << job.first << "\" is running for "
<< absl::ToInt64Seconds(age) << " s"; << absl::ToInt64Seconds(age) << " s";
} }
} }
list_jobs_time_ = current_time; list_jobs_time_ = current_time;
@@ -87,12 +89,12 @@ void PendingJobRegistry::ListAllJobs() {
for (auto& job : pending_jobs_) { for (auto& job : pending_jobs_) {
auto age = current_time - job.second; auto age = current_time - job.second;
LOG(INFO) << "Task \"" << job.first << "\" is waiting for " LOG(INFO) << "Task \"" << job.first << "\" is waiting for "
<< absl::ToInt64Seconds(age) << " s"; << absl::ToInt64Seconds(age) << " s";
} }
for (auto& job : running_jobs_) { for (auto& job : running_jobs_) {
auto age = current_time - job.second; auto age = current_time - job.second;
LOG(INFO) << "Task \"" << job.first << "\" is running for " LOG(INFO) << "Task \"" << job.first << "\" is running for "
<< absl::ToInt64Seconds(age) << " s"; << absl::ToInt64Seconds(age) << " s";
} }
list_jobs_time_ = current_time; list_jobs_time_ = current_time;
} }
+1 -3
View File
@@ -66,9 +66,7 @@ class MediumSocket : public Socket {
virtual void FeedIncomingData(ByteArray data) {} virtual void FeedIncomingData(ByteArray data) {}
/** Returns true if the socket is a virtual socket. */ /** Returns true if the socket is a virtual socket. */
virtual bool IsVirtualSocket() { virtual bool IsVirtualSocket() { return false; }
return false;
}
/** Adds a listener to be invoked when the socket is closed. */ /** Adds a listener to be invoked when the socket is closed. */
void AddOnSocketClosedListener( void AddOnSocketClosedListener(
+3 -3
View File
@@ -14,17 +14,17 @@
#include "internal/platform/wifi_direct.h" #include "internal/platform/wifi_direct.h"
#include "internal/platform/logging.h"
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "internal/platform/cancellation_flag.h" #include "internal/platform/cancellation_flag.h"
#include "internal/platform/logging.h"
namespace nearby { namespace nearby {
WifiDirectSocket WifiDirectMedium::ConnectToService( WifiDirectSocket WifiDirectMedium::ConnectToService(
absl::string_view ip_address, int port, absl::string_view ip_address, int port,
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
LOG(INFO) << "WifiDirectMedium::ConnectToService: ip address=" LOG(INFO) << "WifiDirectMedium::ConnectToService: ip address=" << ip_address
<< ip_address << ", port=" << port; << ", port=" << port;
return WifiDirectSocket( return WifiDirectSocket(
impl_->ConnectToService(ip_address, port, cancellation_flag)); impl_->ConnectToService(ip_address, port, cancellation_flag));
} }
+1 -2
View File
@@ -122,8 +122,7 @@ class WifiDirectServerSocket final {
WifiDirectSocket Accept() { WifiDirectSocket Accept() {
std::unique_ptr<api::WifiDirectSocket> socket = impl_->Accept(); std::unique_ptr<api::WifiDirectSocket> socket = impl_->Accept();
if (!socket) { if (!socket) {
LOG(INFO) LOG(INFO) << "WifiDirectServerSocket Accept() failed on server socket: ";
<< "WifiDirectServerSocket Accept() failed on server socket: ";
} }
return WifiDirectSocket(std::move(socket)); return WifiDirectSocket(std::move(socket));
} }
+25 -32
View File
@@ -20,12 +20,12 @@
#include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_map.h"
#include "internal/platform/cancellation_flag.h" #include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/wifi_utils.h"
#include "internal/platform/logging.h" #include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h" #include "internal/platform/mutex_lock.h"
#include "internal/platform/nsd_service_info.h" #include "internal/platform/nsd_service_info.h"
#include "internal/platform/output_stream.h" #include "internal/platform/output_stream.h"
#include "internal/platform/socket.h" #include "internal/platform/socket.h"
#include "internal/platform/implementation/wifi_utils.h"
namespace nearby { namespace nearby {
using location::nearby::proto::connections::Medium; using location::nearby::proto::connections::Medium;
@@ -44,15 +44,14 @@ MediumSocket* WifiLanSocket::CreateVirtualSocket(
auto virtual_socket = std::make_shared<WifiLanSocket>(outputstream); auto virtual_socket = std::make_shared<WifiLanSocket>(outputstream);
virtual_socket->impl_ = this->impl_; virtual_socket->impl_ = this->impl_;
LOG(WARNING) << "Created the virtual socket for Medium: " LOG(WARNING) << "Created the virtual socket for Medium: "
<< Medium_Name(virtual_socket->GetMedium()); << Medium_Name(virtual_socket->GetMedium());
if (virtual_sockets_ptr_ == nullptr) { if (virtual_sockets_ptr_ == nullptr) {
virtual_sockets_ptr_ = virtual_sockets_ptr; virtual_sockets_ptr_ = virtual_sockets_ptr;
} }
(*virtual_sockets_ptr_)[salted_service_id_hash_key] = virtual_socket; (*virtual_sockets_ptr_)[salted_service_id_hash_key] = virtual_socket;
LOG(INFO) << "virtual_sockets_ size: " LOG(INFO) << "virtual_sockets_ size: " << virtual_sockets_ptr_->size();
<< virtual_sockets_ptr_->size();
return virtual_socket.get(); return virtual_socket.get();
} }
@@ -71,7 +70,7 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_id,
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
if (service_type_to_callback_map_.contains(service_type)) { if (service_type_to_callback_map_.contains(service_type)) {
LOG(INFO) << "WifiLan Discovery already start with service_type=" LOG(INFO) << "WifiLan Discovery already start with service_type="
<< service_type << "; impl=" << &GetImpl(); << service_type << "; impl=" << &GetImpl();
return false; return false;
} }
} }
@@ -84,35 +83,31 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_id,
const auto& it = service_type_to_callback_map_.find(service_type); const auto& it = service_type_to_callback_map_.find(service_type);
if (it == service_type_to_callback_map_.end()) { if (it == service_type_to_callback_map_.end()) {
LOG(ERROR) LOG(ERROR) << "There is no callback found for service_type="
<< "There is no callback found for service_type=" << service_type;
<< service_type;
return; return;
} }
// Check whether service name is in cache. // Check whether service name is in cache.
auto services_it = service_type_to_services_map_.find(service_type); auto services_it = service_type_to_services_map_.find(service_type);
if (services_it == service_type_to_services_map_.end()) { if (services_it == service_type_to_services_map_.end()) {
LOG(ERROR) LOG(ERROR) << "There is no service map found for service_type="
<< "There is no service map found for service_type=" << service_type;
<< service_type;
return; return;
} }
std::string service_name = service_info.GetServiceName(); std::string service_name = service_info.GetServiceName();
auto pair = services_it->second.insert(service_name); auto pair = services_it->second.insert(service_name);
if (!pair.second) { if (!pair.second) {
LOG(INFO) LOG(INFO) << "Discovering (again) service_info=" << &service_info
<< "Discovering (again) service_info=" << &service_info << ", service_type=" << service_type
<< ", service_type=" << service_type << ", service_name=" << service_info.GetServiceName();
<< ", service_name=" << service_info.GetServiceName();
return; return;
} }
LOG(INFO) LOG(INFO) << "Adding service_info=" << &service_info
<< "Adding service_info=" << &service_info << ", service_type=" << service_type
<< ", service_type=" << service_type << ", service_name=" << service_info.GetServiceName();
<< ", service_name=" << service_info.GetServiceName();
std::string service_id = it->second->service_id; std::string service_id = it->second->service_id;
DiscoveredServiceCallback& medium_callback = DiscoveredServiceCallback& medium_callback =
@@ -126,17 +121,16 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_id,
std::string service_name = service_info.GetServiceName(); std::string service_name = service_info.GetServiceName();
auto services_it = service_type_to_services_map_.find(service_type); auto services_it = service_type_to_services_map_.find(service_type);
if (services_it == service_type_to_services_map_.end()) { if (services_it == service_type_to_services_map_.end()) {
LOG(ERROR) LOG(ERROR) << "There is no service map found for service_type="
<< "There is no service map found for service_type=" << service_type;
<< service_type;
return; return;
} }
auto item = services_it->second.extract(service_name); auto item = services_it->second.extract(service_name);
if (item.empty()) return; if (item.empty()) return;
LOG(INFO) << "Removing service_info=" << &service_info LOG(INFO) << "Removing service_info=" << &service_info
<< ", service_type=" << service_type << ", service_type=" << service_type
<< ", service_info_name=" << service_name; << ", service_info_name=" << service_name;
// Callback service lost. // Callback service lost.
const auto& it = service_type_to_callback_map_.find(service_type); const auto& it = service_type_to_callback_map_.find(service_type);
if (it != service_type_to_callback_map_.end()) { if (it != service_type_to_callback_map_.end()) {
@@ -169,9 +163,8 @@ bool WifiLanMedium::StartDiscovery(const std::string& service_id,
service_type_to_callback_map_.erase(service_type); service_type_to_callback_map_.erase(service_type);
service_type_to_services_map_.erase(service_type); service_type_to_services_map_.erase(service_type);
} }
LOG(INFO) << "WifiLan Discovery started for service_type=" LOG(INFO) << "WifiLan Discovery started for service_type=" << service_type
<< service_type << ", impl=" << &GetImpl() << ", impl=" << &GetImpl() << ", success=" << success;
<< ", success=" << success;
return success; return success;
} }
@@ -184,8 +177,8 @@ bool WifiLanMedium::StopDiscovery(const std::string& service_type) {
if (service_type_to_services_map_.contains(service_type)) { if (service_type_to_services_map_.contains(service_type)) {
service_type_to_services_map_.erase(service_type); service_type_to_services_map_.erase(service_type);
} }
LOG(INFO) << "WifiLan Discovery disabled for service_type=" LOG(INFO) << "WifiLan Discovery disabled for service_type=" << service_type
<< service_type << ", impl=" << &GetImpl(); << ", impl=" << &GetImpl();
return impl_->StopDiscovery(service_type); return impl_->StopDiscovery(service_type);
} }
@@ -193,7 +186,7 @@ WifiLanSocket WifiLanMedium::ConnectToService(
const NsdServiceInfo& remote_service_info, const NsdServiceInfo& remote_service_info,
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
LOG(INFO) << "WifiLanMedium::ConnectToService: remote_service_name=" LOG(INFO) << "WifiLanMedium::ConnectToService: remote_service_name="
<< remote_service_info.GetServiceName(); << remote_service_info.GetServiceName();
return WifiLanSocket( return WifiLanSocket(
impl_->ConnectToService(remote_service_info, cancellation_flag)); impl_->ConnectToService(remote_service_info, cancellation_flag));
} }
@@ -202,8 +195,8 @@ WifiLanSocket WifiLanMedium::ConnectToService(
const std::string& ip_address, int port, const std::string& ip_address, int port,
CancellationFlag* cancellation_flag) { CancellationFlag* cancellation_flag) {
LOG(INFO) << "WifiLanMedium::ConnectToService: ip address=" LOG(INFO) << "WifiLanMedium::ConnectToService: ip address="
<< WifiUtils::GetHumanReadableIpAddress(ip_address) << WifiUtils::GetHumanReadableIpAddress(ip_address)
<< ", port=" << port; << ", port=" << port;
return WifiLanSocket( return WifiLanSocket(
impl_->ConnectToService(ip_address, port, cancellation_flag)); impl_->ConnectToService(ip_address, port, cancellation_flag));
} }
+2 -2
View File
@@ -164,8 +164,8 @@ class WifiLanServerSocket final {
WifiLanSocket Accept() { WifiLanSocket Accept() {
std::unique_ptr<api::WifiLanSocket> socket = impl_->Accept(); std::unique_ptr<api::WifiLanSocket> socket = impl_->Accept();
if (!socket) { if (!socket) {
LOG(INFO) LOG(INFO) << "WifiLanServerSocket Accept() failed on server socket: "
<< "WifiLanServerSocket Accept() failed on server socket: " << this; << this;
} }
return WifiLanSocket(std::move(socket)); return WifiLanSocket(std::move(socket));
} }
+1 -3
View File
@@ -94,9 +94,7 @@ class FakeSocket : public BaseSocket {
explicit FakeSocket(const Connection& connection, explicit FakeSocket(const Connection& connection,
SocketCallback&& socketCallback) SocketCallback&& socketCallback)
: BaseSocket(connection, std::move(socketCallback)) {} : BaseSocket(connection, std::move(socketCallback)) {}
~FakeSocket() override { ~FakeSocket() override { ShutDown(); }
ShutDown();
}
MOCK_METHOD(void, Connect, (), (override)); MOCK_METHOD(void, Connect, (), (override));
void OnReceiveControlPacket(Packet packet) override { void OnReceiveControlPacket(Packet packet) override {
control_packets_.push_back(std::move(packet)); control_packets_.push_back(std::move(packet));
+1 -2
View File
@@ -349,8 +349,7 @@ TEST_F(ClientSocketTest, TestSocketWithRandomDataProvider) {
MutexLock lock(&mutex_); MutexLock lock(&mutex_);
messages_read_.push_back(message); messages_read_.push_back(message);
}, },
.on_error_cb = .on_error_cb = [](absl::Status status) { LOG(ERROR) << status; },
[](absl::Status status) { LOG(ERROR) << status; },
}, },
std::move(provider)); std::move(provider));
socket.Connect(); socket.Connect();
+8 -9
View File
@@ -87,9 +87,9 @@ void ServerSocket::OnReceiveControlPacket(Packet packet) {
// after the initial handshake. // after the initial handshake.
if (state_ != State::kClientConnectionRequest) { if (state_ != State::kClientConnectionRequest) {
LOG(ERROR) << "Not in 'Connection Request' state, but " LOG(ERROR) << "Not in 'Connection Request' state, but "
"incorrectly received control packet of type " "incorrectly received control packet of type "
<< Packet::ControlPacketTypeToString( << Packet::ControlPacketTypeToString(
packet.GetControlCommandNumber()); packet.GetControlCommandNumber());
GetSocketCallback().on_error_cb( GetSocketCallback().on_error_cb(
absl::InvalidArgumentError("Unexpected control packet")); absl::InvalidArgumentError("Unexpected control packet"));
return; return;
@@ -97,9 +97,9 @@ void ServerSocket::OnReceiveControlPacket(Packet packet) {
if (packet.GetControlCommandNumber() != if (packet.GetControlCommandNumber() !=
Packet::ControlPacketType::kControlConnectionRequest) { Packet::ControlPacketType::kControlConnectionRequest) {
LOG(ERROR) << "Expected connection request control packet, " LOG(ERROR) << "Expected connection request control packet, "
"received control packet of type " "received control packet of type "
<< Packet::ControlPacketTypeToString( << Packet::ControlPacketTypeToString(
packet.GetControlCommandNumber()); packet.GetControlCommandNumber());
DisconnectInternal( DisconnectInternal(
absl::InvalidArgumentError("Unexpected control packet type.")); absl::InvalidArgumentError("Unexpected control packet type."));
return; return;
@@ -117,8 +117,7 @@ void ServerSocket::OnReceiveControlPacket(Packet packet) {
if (min_protocol_version > kProtocolVersion || if (min_protocol_version > kProtocolVersion ||
max_protocol_version < kProtocolVersion) { max_protocol_version < kProtocolVersion) {
LOG(ERROR) << "Received unexpected min/max protocol versions: " LOG(ERROR) << "Received unexpected min/max protocol versions: "
<< min_protocol_version << " and " << min_protocol_version << " and " << max_protocol_version;
<< max_protocol_version;
DisconnectInternal( DisconnectInternal(
absl::InvalidArgumentError("unexpected protocol versions")); absl::InvalidArgumentError("unexpected protocol versions"));
return; return;
@@ -145,7 +144,7 @@ void ServerSocket::WriteConnectionConfirm() {
kProtocolVersion, max_packet_size_, ""); kProtocolVersion, max_packet_size_, "");
if (!packet.ok()) { if (!packet.ok()) {
LOG(ERROR) << "Failed to create connection confirm packet: " LOG(ERROR) << "Failed to create connection confirm packet: "
<< packet.status(); << packet.status();
DisconnectInternal(packet.status()); DisconnectInternal(packet.status());
return; return;
} }
+3 -4
View File
@@ -90,7 +90,7 @@ absl::Status FppManager::UpdateBleScanResult(uint64_t device_id,
presence_detector_handle_, ble_scan_result, &new_proximity_estimate); presence_detector_handle_, ble_scan_result, &new_proximity_estimate);
if (status_code == kNoComputedProximityEstimate) { if (status_code == kNoComputedProximityEstimate) {
LOG(INFO) << "Insufficient number of scan results available to " LOG(INFO) << "Insufficient number of scan results available to "
"compute proximity state"; "compute proximity state";
return absl::OkStatus(); return absl::OkStatus();
} }
if (status_code == kSuccess) { if (status_code == kSuccess) {
@@ -142,9 +142,8 @@ void FppManager::CheckPresenceZoneChanged(uint64_t device_id,
ProximityEstimate old_estimate, ProximityEstimate old_estimate,
ProximityEstimate new_estimate) { ProximityEstimate new_estimate) {
if (old_estimate.proximity_state != new_estimate.proximity_state) { if (old_estimate.proximity_state != new_estimate.proximity_state) {
LOG(WARNING) LOG(WARNING) << "Updating zone transition callbacks with new zone. Zone="
<< "Updating zone transition callbacks with new zone. Zone=" << static_cast<int>(new_estimate.proximity_state);
<< static_cast<int>(new_estimate.proximity_state);
for (auto& pair : zone_transition_callbacks_) { for (auto& pair : zone_transition_callbacks_) {
pair.second.on_proximity_zone_changed( pair.second.on_proximity_zone_changed(
device_id, device_id,
+1 -1
View File
@@ -67,7 +67,7 @@ int GetMask(const DataElement& element) {
} }
} }
LOG(WARNING) << "Data Element " << type LOG(WARNING) << "Data Element " << type
<< " not supported in base advertisement"; << " not supported in base advertisement";
return kEmptyMask; return kEmptyMask;
} }
@@ -147,8 +147,8 @@ absl::StatusOr<DataElement> ParseDataElement(const absl::string_view input,
absl::BytesToHexString(input), input.size(), index)); absl::BytesToHexString(input), input.size(), index));
} }
VLOG(1) << "Type: " << static_cast<int>(data_type) VLOG(1) << "Type: " << static_cast<int>(data_type)
<< " length: " << static_cast<int>(length) << " DE: " << " length: " << static_cast<int>(length)
<< absl::BytesToHexString(input.substr(start, length)); << " DE: " << absl::BytesToHexString(input.substr(start, length));
return DataElement(data_type, input.substr(start, length)); return DataElement(data_type, input.substr(start, length));
} }
} // namespace } // namespace
@@ -157,9 +157,9 @@ void DecodeBaseAction(absl::string_view serialized_action,
Advertisement& decoded_advertisement) { Advertisement& decoded_advertisement) {
if (serialized_action.empty() || serialized_action.size() > 3) { if (serialized_action.empty() || serialized_action.size() > 3) {
LOG(WARNING) << "Base NP action \'" LOG(WARNING) << "Base NP action \'"
<< absl::BytesToHexString(serialized_action) << absl::BytesToHexString(serialized_action)
<< "\' has wrong length " << serialized_action.size() << "\' has wrong length " << serialized_action.size()
<< " , expected size in range [1 - 3]"; << " , expected size in range [1 - 3]";
return; return;
} }
// Action, 0-2 bytes in Big Endian order. // Action, 0-2 bytes in Big Endian order.
@@ -213,7 +213,7 @@ absl::Status DecryptDataElements(
DecryptLdt(credentials, salt, encrypted, decoded_advertisement); DecryptLdt(credentials, salt, encrypted, decoded_advertisement);
if (!decrypted.ok()) { if (!decrypted.ok()) {
LOG(WARNING) << "Failed to decrypt advertisement, status: " LOG(WARNING) << "Failed to decrypt advertisement, status: "
<< decrypted.status(); << decrypted.status();
return decrypted.status(); return decrypted.status();
} }
size_t index = 0; size_t index = 0;
@@ -222,7 +222,7 @@ absl::Status DecryptDataElements(
ParseDataElement(*decrypted, index); ParseDataElement(*decrypted, index);
if (!internal_elem.ok()) { if (!internal_elem.ok()) {
LOG(WARNING) << "Failed to read data element, status: " LOG(WARNING) << "Failed to read data element, status: "
<< internal_elem.status(); << internal_elem.status();
return internal_elem.status(); return internal_elem.status();
} }
if (internal_elem->GetType() == DataElement::kActionFieldType) { if (internal_elem->GetType() == DataElement::kActionFieldType) {
@@ -238,8 +238,7 @@ absl::StatusOr<Advertisement> AdvertisementDecoderImpl::DecodeAdvertisement(
absl::string_view advertisement) { absl::string_view advertisement) {
Advertisement decoded_advertisement = Advertisement{}; Advertisement decoded_advertisement = Advertisement{};
std::vector<DataElement> result; std::vector<DataElement> result;
LOG(INFO) << "Advertisement: " LOG(INFO) << "Advertisement: " << absl::BytesToHexString(advertisement);
<< absl::BytesToHexString(advertisement);
if (advertisement.empty()) { if (advertisement.empty()) {
return absl::OutOfRangeError("Empty advertisement"); return absl::OutOfRangeError("Empty advertisement");
} }
@@ -255,8 +254,7 @@ absl::StatusOr<Advertisement> AdvertisementDecoderImpl::DecodeAdvertisement(
while (index < advertisement.size()) { while (index < advertisement.size()) {
absl::StatusOr<DataElement> elem = ParseDataElement(advertisement, index); absl::StatusOr<DataElement> elem = ParseDataElement(advertisement, index);
if (!elem.ok()) { if (!elem.ok()) {
LOG(WARNING) << "Failed to read data element, status: " LOG(WARNING) << "Failed to read data element, status: " << elem.status();
<< elem.status();
return elem.status(); return elem.status();
} }
if (IsIdentity(elem->GetType())) { if (IsIdentity(elem->GetType())) {
@@ -57,9 +57,8 @@ void AddActionsToAdvertisement(const nearby_protocol::V0Actions& parsed_actions,
for (const auto action : kAllActionBits) { for (const auto action : kAllActionBits) {
auto action_type = MapAction(action); auto action_type = MapAction(action);
if (!action_type.ok()) { if (!action_type.ok()) {
LOG(WARNING) LOG(WARNING) << "Advertisement contains an unsupported action bit: "
<< "Advertisement contains an unsupported action bit: " << (int)action;
<< (int)action;
continue; continue;
} }
if (parsed_actions.HasAction(*action_type)) { if (parsed_actions.HasAction(*action_type)) {
@@ -64,7 +64,7 @@ absl::Status AppendDataElement(unsigned data_type,
auto header = CreateDataElementHeader(data_element.size(), data_type); auto header = CreateDataElementHeader(data_element.size(), data_type);
if (!header.ok()) { if (!header.ok()) {
LOG(WARNING) << "Can't add Data element type: " << data_type LOG(WARNING) << "Can't add Data element type: " << data_type
<< ", length: " << data_element.size(); << ", length: " << data_element.size();
return header.status(); return header.status();
} }
output.push_back(*header); output.push_back(*header);
@@ -152,7 +152,7 @@ AdvertisementFactory::CreateBaseNpAdvertisement(
return result; return result;
} }
VLOG(1) << "Unencrypted advertisement payload " VLOG(1) << "Unencrypted advertisement payload "
<< absl::BytesToHexString(unencrypted); << absl::BytesToHexString(unencrypted);
absl::StatusOr<std::string> encrypted = absl::StatusOr<std::string> encrypted =
EncryptDataElements(*credential, request.salt, unencrypted); EncryptDataElements(*credential, request.salt, unencrypted);
if (!encrypted.ok()) { if (!encrypted.ok()) {
@@ -65,11 +65,10 @@ bool AdvertisementFilter::MatchesScanFilter(
!(std::find( !(std::find(
requested_identity_types.begin(), requested_identity_types.end(), requested_identity_types.begin(), requested_identity_types.end(),
advertisement.identity_type) != requested_identity_types.end())) { advertisement.identity_type) != requested_identity_types.end())) {
LOG(INFO) LOG(INFO) << "Skipping advertisement with identity type: "
<< "Skipping advertisement with identity type: " << advertisement.identity_type
<< advertisement.identity_type << " because that identity type was not requested in the scan "
<< " because that identity type was not requested in the scan " "request";
"request";
return false; return false;
} }
@@ -93,8 +93,7 @@ absl::StatusOr<BaseBroadcastRequest> BaseBroadcastRequest::Create(
return absl::InvalidArgumentError("Missing broadcast sections"); return absl::InvalidArgumentError("Missing broadcast sections");
} }
if (presence_request.sections.size() > 1) { if (presence_request.sections.size() > 1) {
LOG(WARNING) LOG(WARNING) << "Only first section is used in BLE 4.2 advertisement";
<< "Only first section is used in BLE 4.2 advertisement";
} }
const PresenceBroadcast::BroadcastSection& section = const PresenceBroadcast::BroadcastSection& section =
presence_request.sections.front(); presence_request.sections.front();
+8 -12
View File
@@ -87,8 +87,7 @@ absl::StatusOr<BroadcastSessionId> BroadcastManager::StartBroadcast(
absl::StatusOr<BaseBroadcastRequest> request = absl::StatusOr<BaseBroadcastRequest> request =
BaseBroadcastRequest::Create(broadcast_request); BaseBroadcastRequest::Create(broadcast_request);
if (!request.ok()) { if (!request.ok()) {
LOG(WARNING) << "Invalid broadcast request, reason: " LOG(WARNING) << "Invalid broadcast request, reason: " << request.status();
<< request.status();
callback.start_broadcast_cb(request.status()); callback.start_broadcast_cb(request.status());
return request.status(); return request.status();
} }
@@ -124,9 +123,8 @@ void BroadcastManager::FetchCredentials(
std::vector<::nearby::internal::LocalCredential>> std::vector<::nearby::internal::LocalCredential>>
credentials) { credentials) {
if (!credentials.ok()) { if (!credentials.ok()) {
LOG(WARNING) LOG(WARNING) << "Failed to fetch credentials, status: "
<< "Failed to fetch credentials, status: " << credentials.status();
<< credentials.status();
NotifyStartCallbackStatus(id, credentials.status()); NotifyStartCallbackStatus(id, credentials.status());
return; return;
} }
@@ -143,10 +141,9 @@ void BroadcastManager::FetchCredentials(
selector, std::move(*credential), selector, std::move(*credential),
{[](absl::Status status) { {[](absl::Status status) {
if (!status.ok()) { if (!status.ok()) {
LOG(WARNING) LOG(WARNING) << "Failed to update private "
<< "Failed to update private " "credential, status: "
"credential, status: " << status;
<< status;
} }
}}); }});
} }
@@ -191,7 +188,7 @@ absl::optional<LocalCredential> BroadcastManager::Advertise( // NOLINT
AdvertisementFactory().CreateAdvertisement(broadcast_request, credential); AdvertisementFactory().CreateAdvertisement(broadcast_request, credential);
if (!advertisement.ok()) { if (!advertisement.ok()) {
LOG(WARNING) << "Can't create advertisement, reason: " LOG(WARNING) << "Can't create advertisement, reason: "
<< advertisement.status(); << advertisement.status();
NotifyStartCallbackStatus(id, advertisement.status()); NotifyStartCallbackStatus(id, advertisement.status());
return absl::optional<LocalCredential>(); // NOLINT return absl::optional<LocalCredential>(); // NOLINT
} }
@@ -233,8 +230,7 @@ void BroadcastManager::StopBroadcast(BroadcastSessionId id) {
"stop-broadcast", [this, id]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor_) { "stop-broadcast", [this, id]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(executor_) {
auto it = sessions_.find(id); auto it = sessions_.find(id);
if (it == sessions_.end()) { if (it == sessions_.end()) {
VLOG(1) << absl::StrFormat("BroadcastSession(0x%x) not found", VLOG(1) << absl::StrFormat("BroadcastSession(0x%x) not found", id);
id);
return; return;
} }
it->second.StopAdvertising(); it->second.StopAdvertising();
@@ -29,12 +29,12 @@
#include "absl/time/time.h" #include "absl/time/time.h"
#include "absl/types/span.h" #include "absl/types/span.h"
#include "absl/types/variant.h" #include "absl/types/variant.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/count_down_latch.h"
#include "internal/crypto_cros/aead.h" #include "internal/crypto_cros/aead.h"
#include "internal/crypto_cros/ec_private_key.h" #include "internal/crypto_cros/ec_private_key.h"
#include "internal/crypto_cros/hkdf.h" #include "internal/crypto_cros/hkdf.h"
#include "internal/platform/base64_utils.h" #include "internal/platform/base64_utils.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/crypto.h" #include "internal/platform/crypto.h"
#include "internal/platform/future.h" #include "internal/platform/future.h"
#include "internal/platform/implementation/credential_callbacks.h" #include "internal/platform/implementation/credential_callbacks.h"
@@ -147,8 +147,7 @@ void CredentialManagerImpl::GenerateCredentials(
callback = std::move(credentials_generated_cb), callback = std::move(credentials_generated_cb),
public_credentials](absl::Status status) mutable { public_credentials](absl::Status status) mutable {
if (!status.ok()) { if (!status.ok()) {
LOG(WARNING) LOG(WARNING) << "Save credentials failed with: " << status;
<< "Save credentials failed with: " << status;
std::move(callback.credentials_generated_cb)(status); std::move(callback.credentials_generated_cb)(status);
return; return;
} }
@@ -514,8 +513,8 @@ CredentialManagerImpl::GetSubscribedIdentities(
void CredentialManagerImpl::OnCredentialsChanged( void CredentialManagerImpl::OnCredentialsChanged(
absl::string_view manager_app_id, absl::string_view account_name, absl::string_view manager_app_id, absl::string_view account_name,
PublicCredentialType credential_type) { PublicCredentialType credential_type) {
LOG(INFO) << "OnCredentialsChanged for app " << manager_app_id LOG(INFO) << "OnCredentialsChanged for app " << manager_app_id << ", account "
<< ", account " << account_name; << account_name;
for (IdentityType identity_type : for (IdentityType identity_type :
GetSubscribedIdentities(manager_app_id, account_name, credential_type)) { GetSubscribedIdentities(manager_app_id, account_name, credential_type)) {
CredentialSelector credential_selector = { CredentialSelector credential_selector = {
@@ -535,9 +534,8 @@ CredentialManagerImpl::CreateNotifySubscribersCallback(SubscriberKey key) {
[this, [this,
key](absl::StatusOr<std::vector<SharedCredential>> credentials) { key](absl::StatusOr<std::vector<SharedCredential>> credentials) {
if (!credentials.ok()) { if (!credentials.ok()) {
LOG(WARNING) LOG(WARNING) << "Failed to get public credentials: error code: "
<< "Failed to get public credentials: error code: " << credentials.status();
<< credentials.status();
return; return;
} }
RunOnServiceControllerThread( RunOnServiceControllerThread(
@@ -555,13 +553,13 @@ void CredentialManagerImpl::NotifySubscribers(
// without locking. // without locking.
auto it = subscribers_.find(key); auto it = subscribers_.find(key);
if (it == subscribers_.end()) { if (it == subscribers_.end()) {
LOG(WARNING) LOG(WARNING) << "No subscribers for (app: "
<< "No subscribers for (app: " << key.credential_selector.manager_app_id << key.credential_selector.manager_app_id
<< ", account: " << key.credential_selector.account_name << ", account: " << key.credential_selector.account_name
<< ", identity type: " << ", identity type: "
<< static_cast<int>(key.credential_selector.identity_type) << static_cast<int>(key.credential_selector.identity_type)
<< ", credential type: " << static_cast<int>(key.public_credential_type) << ", credential type: "
<< ")"; << static_cast<int>(key.public_credential_type) << ")";
return; return;
} }
for (auto& subscriber : it->second) { for (auto& subscriber : it->second) {
@@ -633,8 +631,7 @@ void CredentialManagerImpl::CheckCredentialsAndRefillIfNeeded(
valid_shared_credentials.push_back(credential); valid_shared_credentials.push_back(credential);
} }
} else { } else {
LOG(ERROR) LOG(ERROR) << "Bad parameters for CheckCredentialsAndRefillIfNeeded";
<< "Bad parameters for CheckCredentialsAndRefillIfNeeded";
return; return;
} }
@@ -803,8 +800,7 @@ void CredentialManagerImpl::OnCredentialRefillComplete(
std::optional<GetPublicCredentialsResultCallback> std::optional<GetPublicCredentialsResultCallback>
callback_for_shared_credentials) { callback_for_shared_credentials) {
if (!save_credentials_status.ok()) { if (!save_credentials_status.ok()) {
LOG(ERROR) << "Save credentials failed with: " LOG(ERROR) << "Save credentials failed with: " << save_credentials_status;
<< save_credentials_status;
if (callback_for_local_credentials.has_value()) { if (callback_for_local_credentials.has_value()) {
callback_for_local_credentials.value().credentials_fetched_cb( callback_for_local_credentials.value().credentials_fetched_cb(
save_credentials_status); save_credentials_status);
@@ -829,7 +825,7 @@ bool CredentialManagerImpl::WaitForLatch(absl::string_view method_name,
Exception await_exception = latch->Await(); Exception await_exception = latch->Await();
if (!await_exception.Ok()) { if (!await_exception.Ok()) {
LOG(ERROR) << "Blocked in " << method_name LOG(ERROR) << "Blocked in " << method_name
<< " with exeception code: " << await_exception.value; << " with exeception code: " << await_exception.value;
return false; return false;
} }
return true; return true;
+6 -8
View File
@@ -131,8 +131,7 @@ void ScanManager::NotifyFoundBle(ScanSessionId id, BleAdvertisementData data,
std::string remote_address = absl::StrCat(absl::Hex(peripheral_id)); std::string remote_address = absl::StrCat(absl::Hex(peripheral_id));
if (it->second.advertisement_filter.MatchesScanFilter(*advert)) { if (it->second.advertisement_filter.MatchesScanFilter(*advert)) {
internal::DeviceIdentityMetaData device_identity_metadata; internal::DeviceIdentityMetaData device_identity_metadata;
device_identity_metadata.set_bluetooth_mac_address( device_identity_metadata.set_bluetooth_mac_address(remote_address);
remote_address);
if (!device_unique_id_to_endpoint_id_map_.contains(peripheral_id)) { if (!device_unique_id_to_endpoint_id_map_.contains(peripheral_id)) {
PresenceDevice device(DeviceMotion(), device_identity_metadata, PresenceDevice device(DeviceMotion(), device_identity_metadata,
@@ -150,12 +149,12 @@ void ScanManager::NotifyFoundBle(ScanSessionId id, BleAdvertisementData data,
} }
device_unique_id_to_endpoint_id_map_.emplace(peripheral_id, device_unique_id_to_endpoint_id_map_.emplace(peripheral_id,
device.GetEndpointId()); device.GetEndpointId());
it->second.callback.on_discovered_cb(std::move(device)); it->second.callback.on_discovered_cb(std::move(device));
} else { } else {
PresenceDevice device( PresenceDevice device(
device_unique_id_to_endpoint_id_map_.at(peripheral_id)); device_unique_id_to_endpoint_id_map_.at(peripheral_id));
device.SetDeviceIdentityMetaData(device_identity_metadata); device.SetDeviceIdentityMetaData(device_identity_metadata);
// Ok if the advertisement is for trusted/private identity. // Ok if the advertisement is for trusted/private identity.
if (advert->public_credential.ok()) { if (advert->public_credential.ok()) {
@@ -187,7 +186,7 @@ void ScanManager::NotifyLostBle(ScanSessionId id,
device_identity_metadata.set_bluetooth_mac_address( device_identity_metadata.set_bluetooth_mac_address(
std::string(remote_address)); std::string(remote_address));
PresenceDevice device( PresenceDevice device(
device_unique_id_to_endpoint_id_map_.at(peripheral_id)); device_unique_id_to_endpoint_id_map_.at(peripheral_id));
device.SetDeviceIdentityMetaData(device_identity_metadata); device.SetDeviceIdentityMetaData(device_identity_metadata);
device_unique_id_to_endpoint_id_map_.erase(peripheral_id); device_unique_id_to_endpoint_id_map_.erase(peripheral_id);
@@ -222,9 +221,8 @@ void ScanManager::FetchCredentials(ScanSessionId id,
// Not fetching for PUBLIC. // Not fetching for PUBLIC.
if (selector.identity_type == internal::IDENTITY_TYPE_UNSPECIFIED || if (selector.identity_type == internal::IDENTITY_TYPE_UNSPECIFIED ||
selector.identity_type == internal::IDENTITY_TYPE_PUBLIC) { selector.identity_type == internal::IDENTITY_TYPE_PUBLIC) {
LOG(INFO) << __func__ LOG(INFO) << __func__ << ": skip feteching creds for identity type: "
<< ": skip feteching creds for identity type: " << selector.identity_type;
<< selector.identity_type;
continue; continue;
} }
credential_manager_->GetPublicCredentials( credential_manager_->GetPublicCredentials(
+13 -14
View File
@@ -98,18 +98,18 @@ class ScanManagerTest : public testing::Test {
} }
ScanCallback MakeDefaultScanCallback() { ScanCallback MakeDefaultScanCallback() {
return {.start_scan_cb = return {
[this](absl::Status status) { .start_scan_cb =
if (status.ok()) { [this](absl::Status status) {
start_latch_.CountDown(); if (status.ok()) {
} start_latch_.CountDown();
}, }
.on_discovered_cb = },
[this](PresenceDevice pd) { found_latch_.CountDown(); }, .on_discovered_cb =
.on_updated_cb = [this](PresenceDevice pd) { found_latch_.CountDown(); },
[this](PresenceDevice pd) { updated_latch_.CountDown(); }, .on_updated_cb =
.on_lost_cb = [this](PresenceDevice pd) { updated_latch_.CountDown(); },
[this](PresenceDevice pd) { lost_latch_.CountDown(); }}; .on_lost_cb = [this](PresenceDevice pd) { lost_latch_.CountDown(); }};
} }
std::vector<nearby::internal::IdentityType> MakeDefaultIdentityTypes() { std::vector<nearby::internal::IdentityType> MakeDefaultIdentityTypes() {
@@ -319,8 +319,7 @@ TEST_F(ScanManagerTest, StopOneSessionFromAnotherDeadlock) {
}, },
.on_discovered_cb = .on_discovered_cb =
[&](PresenceDevice pd) { [&](PresenceDevice pd) {
LOG(INFO) LOG(INFO) << "scansession2 found";
<< "scansession2 found";
found_latch2.CountDown(); found_latch2.CountDown();
manager.StopScan(scan_session); manager.StopScan(scan_session);
}}; }};
+9 -11
View File
@@ -17,6 +17,7 @@
#include <optional> #include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include "absl/strings/string_view.h" #include "absl/strings/string_view.h"
#include "absl/time/time.h" #include "absl/time/time.h"
#include "absl/types/variant.h" #include "absl/types/variant.h"
@@ -51,7 +52,7 @@ std::string AuthenticationErrorToString(AuthenticationStatus status) {
return "AuthenticationStatus::kFailure"; return "AuthenticationStatus::kFailure";
} }
LOG(ERROR) << "Unexpected value for AuthenticationStatus: " LOG(ERROR) << "Unexpected value for AuthenticationStatus: "
<< static_cast<int>(status); << static_cast<int>(status);
return "AuthenticationStatus::kUnknown"; return "AuthenticationStatus::kUnknown";
} }
@@ -131,16 +132,14 @@ AuthenticationStatus PresenceDeviceProvider::AuthenticateAsInitiator(
&shared_secret]( &shared_secret](
auto status_or_credentials) { auto status_or_credentials) {
if (!status_or_credentials.ok()) { if (!status_or_credentials.ok()) {
LOG(INFO) LOG(INFO) << __func__ << ": failure to fetch local credentials";
<< __func__ << ": failure to fetch local credentials";
response.Set(AuthenticationStatus::kFailure); response.Set(AuthenticationStatus::kFailure);
return; return;
} }
auto credential = GetValidCredential(status_or_credentials.value()); auto credential = GetValidCredential(status_or_credentials.value());
if (!credential.has_value()) { if (!credential.has_value()) {
LOG(INFO) LOG(INFO) << __func__ << ": failure to find a valid local credential";
<< __func__ << ": failure to find a valid local credential";
response.Set(AuthenticationStatus::kFailure); response.Set(AuthenticationStatus::kFailure);
return; return;
} }
@@ -176,7 +175,7 @@ AuthenticationStatus PresenceDeviceProvider::AuthenticateAsInitiator(
CHECK(result.ok()); CHECK(result.ok());
LOG(INFO) << "Future:[" << __func__ << "] completed with status:" LOG(INFO) << "Future:[" << __func__ << "] completed with status:"
<< AuthenticationErrorToString(result.result()); << AuthenticationErrorToString(result.result());
return result.result(); return result.result();
} }
@@ -203,8 +202,7 @@ bool PresenceDeviceProvider::WriteToRemoteDevice(
/*ukey2_secret=*/shared_secret, /*local_credential=*/local_credential, /*ukey2_secret=*/shared_secret, /*local_credential=*/local_credential,
/*shared_credential=*/shared_credential.value()); /*shared_credential=*/shared_credential.value());
if (!status_or_initiator_data.ok()) { if (!status_or_initiator_data.ok()) {
LOG(INFO) << __func__ LOG(INFO) << __func__ << ": failure to build signed message as initiator";
<< ": failure to build signed message as initiator";
return false; return false;
} }
@@ -232,8 +230,8 @@ bool PresenceDeviceProvider::ReadAndVerifyRemoteDeviceData(
&shared_secret]( &shared_secret](
auto status_or_credentials) { auto status_or_credentials) {
if (!status_or_credentials.ok()) { if (!status_or_credentials.ok()) {
LOG(INFO) LOG(INFO) << __func__
<< __func__ << ": failure to fetch local public credentials"; << ": failure to fetch local public credentials";
read_and_verify_result.Set(/*success=*/false); read_and_verify_result.Set(/*success=*/false);
return; return;
} }
@@ -255,7 +253,7 @@ bool PresenceDeviceProvider::ReadAndVerifyRemoteDeviceData(
LOG(INFO) << __func__ << ": Waiting for future to complete"; LOG(INFO) << __func__ << ": Waiting for future to complete";
ExceptionOr<bool> result = read_and_verify_result.Get(); ExceptionOr<bool> result = read_and_verify_result.Get();
LOG(INFO) << "Future:[" << __func__ LOG(INFO) << "Future:[" << __func__
<< "] completed with status:" << result.result(); << "] completed with status:" << result.result();
return result.result(); return result.result();
} }