Merged from google/nearby main

This commit is contained in:
lasan
2024-10-22 11:27:36 +05:30
988 changed files with 175061 additions and 15634 deletions
+22 -3
View File
@@ -23,8 +23,27 @@ cc_library(
"//fastpair:__subpackages__",
"//location/nearby/analytics/cpp:__subpackages__",
"//location/nearby/cpp/experiments:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
"//internal/proto/analytics:connections_log_cc_proto",
"//internal/proto/analytics:fast_pair_log_cc_proto",
"//sharing/proto/analytics:sharing_log_cc_proto",
],
)
cc_library(
name = "mock_event_logger",
testonly = True,
hdrs = [
"mock_event_logger.h",
"sharing_log_matchers.h",
],
compatible_with = ["//buildenv/target:non_prod"],
visibility = ["//visibility:public"],
deps = [
":event_logger",
"@com_google_googletest//:gtest_for_library_testonly",
"@com_google_protobuf//:protobuf_lite",
],
deps = ["@com_google_protobuf//:protobuf"],
)
+7 -2
View File
@@ -15,7 +15,9 @@
#ifndef NEARBY_ANALYTICS_EVENT_LOGGER_H_
#define NEARBY_ANALYTICS_EVENT_LOGGER_H_
#include "google/protobuf/message_lite.h"
#include "internal/proto/analytics/connections_log.pb.h"
#include "internal/proto/analytics/fast_pair_log.pb.h"
#include "sharing/proto/analytics/nearby_sharing_log.pb.h"
namespace nearby {
namespace analytics {
@@ -29,7 +31,10 @@ class EventLogger {
// Logs the proto details. Might block to do I/O, e.g. upload
// synchronously to some metrics server.
virtual void Log(const ::google::protobuf::MessageLite& message) = 0;
virtual void Log(
const location::nearby::analytics::proto::ConnectionsLog& message) = 0;
virtual void Log(const sharing::analytics::proto::SharingLog& message) = 0;
virtual void Log(const nearby::proto::fastpair::FastPairLog& message) = 0;
};
} // namespace analytics
+40
View File
@@ -0,0 +1,40 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_MOCK_EVENT_LOGGER_H_
#define THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_MOCK_EVENT_LOGGER_H_
#include "gmock/gmock.h"
#include "internal/analytics/event_logger.h"
namespace nearby::analytics {
class MockEventLogger : public ::nearby::analytics::EventLogger {
public:
MockEventLogger() = default;
~MockEventLogger() override = default;
MOCK_METHOD(
void, Log,
(const location::nearby::analytics::proto::ConnectionsLog& message),
(override));
MOCK_METHOD(void, Log, (const sharing::analytics::proto::SharingLog& message),
(override));
MOCK_METHOD(void, Log, (const nearby::proto::fastpair::FastPairLog& message),
(override));
};
} // namespace nearby::analytics
#endif // THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_MOCK_EVENT_LOGGER_H_
+64
View File
@@ -0,0 +1,64 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_SHARING_LOG_MATCHERS_H_
#define THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_SHARING_LOG_MATCHERS_H_
#include "gmock/gmock.h"
namespace nearby::analytics {
MATCHER_P(HasCategory, category, "has category") {
return arg.event_category() == category;
}
MATCHER_P(HasEventType, event_type, "has event type") {
return arg.event_type() == event_type;
}
MATCHER_P(HasAction, action, "has action") {
return arg.action() == action;
}
MATCHER_P(HasSessionId, session_id, "has session id") {
return arg.session_id() == session_id;
}
MATCHER_P(HasDurationMillis, duration_millis, "has duration millis") {
return arg.duration_millis() == duration_millis;
}
MATCHER_P(SharingLogHasStatus, status, "has status") {
return arg.status() == status;
}
MATCHER_P(HasRpcName, rpc_name, "has rpc_name") {
return arg.rpc_name() == rpc_name;
}
MATCHER_P(HasDirection, direction, "has direction") {
return arg.direction() == direction;
}
MATCHER_P(HasErrorCode, error_code, "has error_code") {
return arg.error_code() == error_code;
}
MATCHER_P(HasLatencyMillis, latency_millis, "has latency_millis") {
return arg.latency_millis() == latency_millis;
}
} // namespace nearby::analytics
#endif // THIRD_PARTY_NEARBY_INTERNAL_ANALYTICS_SHARING_LOG_MATCHERS_H_
+38 -16
View File
@@ -1,3 +1,17 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
licenses(["notice"])
cc_library(
@@ -7,17 +21,12 @@ cc_library(
hdrs = [
"observer_list.h",
],
copts = [
"-Ithird_party",
],
visibility = [
"//fastpair:__subpackages__",
"//internal/account:__subpackages__",
"//internal/interop:__pkg__",
"//internal/platform:__pkg__",
"//location/nearby/cpp/experiments:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//internal/test:__pkg__",
"//sharing:__subpackages__",
],
deps = [
"//internal/platform:types",
@@ -34,14 +43,10 @@ cc_library(
hdrs = [
"bluetooth_address.h",
],
copts = [
"-Ithird_party",
],
visibility = [
"//fastpair:__subpackages__",
"//internal:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
"@com_google_absl//absl/strings",
@@ -51,6 +56,13 @@ cc_library(
],
)
cc_library(
name = "files",
srcs = ["files.cc"],
hdrs = ["files.h"],
visibility = ["//visibility:public"],
)
cc_test(
name = "base_test",
size = "small",
@@ -58,10 +70,6 @@ cc_test(
srcs = [
"bluetooth_address_test.cc",
],
copts = [
"-Ithird_party",
],
shard_count = 8,
deps = [
":bluetooth_address",
"@com_github_protobuf_matchers//protobuf-matchers",
@@ -70,3 +78,17 @@ cc_test(
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "files_test",
size = "small",
timeout = "short",
srcs = [
"files_test.cc",
],
deps = [
":files",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_googletest//:gtest_main",
],
)
+118
View File
@@ -0,0 +1,118 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/base/files.h"
#include <cstdint>
#include <filesystem> // NOLINT(build/c++17)
#include <optional>
#include <system_error> // NOLINT(build/c++11)
namespace nearby::sharing {
bool FileExists(const std::filesystem::path& path) {
std::error_code error_code;
if (std::filesystem::exists(path, error_code) &&
!std::filesystem::is_directory(path, error_code)) {
// is_directory returns false on error.
return (!error_code);
}
return false;
}
std::optional<uintmax_t> GetFileSize(const std::filesystem::path& path) {
if (!FileExists(path)) {
return std::nullopt;
}
std::error_code error_code;
uintmax_t size = std::filesystem::file_size(path, error_code);
if (size == static_cast<uintmax_t>(-1)) {
return std::nullopt;
}
return size;
}
bool DirectoryExists(const std::filesystem::path& path) {
std::error_code error_code;
if (std::filesystem::exists(path, error_code) &&
std::filesystem::is_directory(path, error_code)) {
return true;
}
return false;
}
bool RemoveFile(const std::filesystem::path& path) {
if (!FileExists(path)) {
return false;
}
std::error_code error_code;
return std::filesystem::remove(path, error_code);
}
std::optional<std::filesystem::path> GetTemporaryDirectory() {
std::error_code error_code;
std::filesystem::path temp_dir =
std::filesystem::temp_directory_path(error_code);
if (temp_dir.empty()) {
return std::nullopt;
}
return temp_dir;
}
std::filesystem::path CurrentDirectory() {
// temp_directory_path() returns empty path on error.
std::error_code error_code;
return std::filesystem::current_path(error_code);
}
bool Rename(const std::filesystem::path& old_path,
const std::filesystem::path& new_path) {
std::error_code error_code;
std::filesystem::rename(old_path, new_path, error_code);
if (error_code) {
return false;
}
return true;
}
bool CreateDirectories(const std::filesystem::path& path) {
std::error_code error_code;
std::filesystem::create_directories(path, error_code);
if (error_code) {
return false;
}
return true;
}
bool CreateHardLink(const std::filesystem::path& target,
const std::filesystem::path& link_path) {
std::error_code error_code;
std::filesystem::create_hard_link(target, link_path, error_code);
if (error_code) {
return false;
}
return true;
}
bool CopyFileSafely(const std::filesystem::path& old_path,
const std::filesystem::path& new_path) {
std::error_code error_code;
std::filesystem::copy(old_path, new_path, error_code);
if (error_code) {
return false;
}
return true;
}
} // namespace nearby::sharing
+66
View File
@@ -0,0 +1,66 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_INTERNAL_BASE_FILES_H_
#define THIRD_PARTY_NEARBY_INTERNAL_BASE_FILES_H_
#include <cstdint>
#include <filesystem> // NOLINT(build/c++17)
#include <optional>
// This file contains exception safe wrappers to access common std::filesystem
// functions.
namespace nearby::sharing {
// Returns true if path exists and is not a directory.
bool FileExists(const std::filesystem::path& path);
// Returns the size of the file at path, or nullopt if not found or not a file.
std::optional<uintmax_t> GetFileSize(const std::filesystem::path& path);
// Returns true if path exists and is a directory.
bool DirectoryExists(const std::filesystem::path& path);
// Removes the file at path and returns true.
// Returns false if path does not exist, is not a file or cannot be removed.
bool RemoveFile(const std::filesystem::path& path);
// Returns path to a temporary directory if available.
std::optional<std::filesystem::path> GetTemporaryDirectory();
// Returns path to the current directory. On failure returns an empty path.
std::filesystem::path CurrentDirectory();
// Renames the file at old_path to new_path.
// Returns true on success.
bool Rename(const std::filesystem::path& old_path,
const std::filesystem::path& new_path);
// Creates all directory leading to path.
// Returns true on success.
bool CreateDirectories(const std::filesystem::path& path);
// Creates a hard link to target at link_path.
// Returns true on success.
bool CreateHardLink(const std::filesystem::path& target,
const std::filesystem::path& link_path);
// Copies the file at old_path to new_path.
// Returns true on success.
bool CopyFileSafely(const std::filesystem::path& old_path,
const std::filesystem::path& new_path);
} // namespace nearby::sharing
#endif // THIRD_PARTY_NEARBY_INTERNAL_BASE_FILES_H_
+48
View File
@@ -0,0 +1,48 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/base/files.h"
#include <cstdint>
#include <filesystem> // NOLINT
#include <fstream>
#include <ios>
#include <optional>
#include "gtest/gtest.h"
namespace nearby::sharing {
namespace {
TEST(FilesTest, CreateHardLinkSuccess) {
std::filesystem::path temp_dir = testing::TempDir();
std::filesystem::path target = temp_dir / "target";
RemoveFile(target);
std::ofstream ofstream(target, std::ios::app);
ASSERT_EQ(ofstream.rdstate(), std::ios_base::goodbit);
ofstream << "Hello world";
ofstream.flush();
std::optional<uintmax_t> size = GetFileSize(target);
ASSERT_TRUE(size.has_value());
EXPECT_EQ(size.value(), 11);
std::filesystem::path link_path = temp_dir / "link_path";
EXPECT_TRUE(CreateHardLink(target, link_path));
EXPECT_TRUE(FileExists(link_path));
EXPECT_EQ(GetFileSize(link_path), 11);
RemoveFile(link_path);
RemoveFile(target);
}
} // namespace
} // namespace nearby::sharing
+3 -2
View File
@@ -29,12 +29,12 @@ cc_library(
],
deps = [
"//internal/crypto_cros",
"//internal/platform:types",
"@boringssl//:crypto",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:span",
],
)
@@ -50,6 +50,7 @@ cc_test(
],
deps = [
":crypto",
"//internal/platform/implementation/g3", # fixdeps: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:span",
+5 -4
View File
@@ -20,12 +20,13 @@
#include <utility>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "internal/crypto_cros/random.h"
#include "internal/platform/crypto.h"
#include <openssl/base.h>
#include <openssl/evp.h>
namespace crypto {
namespace nearby::crypto {
constexpr size_t kEd25519SignatureSize = 64;
constexpr size_t kEd25519PrivateKeySize = 32;
@@ -97,7 +98,7 @@ absl::StatusOr<Ed25519KeyPair> Ed25519Signer::CreateNewKeyPair(
absl::StatusOr<Ed25519KeyPair> Ed25519Signer::CreateNewKeyPair() {
uint8_t key_seed[kEd25519KeySeedSize] = {0};
RandBytes(key_seed, kEd25519KeySeedSize);
nearby::RandBytes(key_seed, kEd25519KeySeedSize);
return CreateNewKeyPair(
std::string(reinterpret_cast<char *>(key_seed), kEd25519KeySeedSize));
}
@@ -180,4 +181,4 @@ absl::Status Ed25519Verifier::Verify(absl::string_view data,
: absl::InternalError("Signature is invalid.");
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -25,7 +25,7 @@
#include <openssl/digest.h>
#include <openssl/evp.h>
namespace crypto {
namespace nearby::crypto {
#ifdef OPENSSL_IS_BORINGSSL
using CryptoKeyUniquePtr = ::bssl::UniquePtr<EVP_PKEY>;
@@ -73,6 +73,6 @@ class CRYPTO_EXPORT Ed25519Verifier {
CryptoKeyUniquePtr public_key_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_ED25519_H_
+2 -2
View File
@@ -21,7 +21,7 @@
#include "gtest/gtest.h"
#include "absl/strings/escaping.h"
namespace crypto {
namespace nearby::crypto {
namespace {
using ::absl::StatusCode;
@@ -211,4 +211,4 @@ TEST(Ed25519SignerVerifierTest, NewKeypairFromRandomSeedRoundtrip) {
}
} // namespace
} // namespace crypto
} // namespace nearby::crypto
-3
View File
@@ -39,7 +39,6 @@ cc_library(
"hmac.cc",
"nearby_base.cc",
"openssl_util.cc",
"random.cc",
"rsa_private_key.cc",
"secure_hash.cc",
"secure_util.cc",
@@ -58,7 +57,6 @@ cc_library(
"hmac.h",
"nearby_base.h",
"openssl_util.h",
"random.h",
"rsa_private_key.h",
"secure_hash.h",
"secure_util.h",
@@ -93,7 +91,6 @@ cc_test(
"ec_signature_creator_unittest.cc",
"encryptor_unittest.cc",
"hmac_unittest.cc",
"random_unittest.cc",
"rsa_private_key_unittest.cc",
"secure_hash_unittest.cc",
"sha2_unittest.cc",
+3 -4
View File
@@ -32,10 +32,9 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/nearby_base.h"
#include "internal/crypto_cros/openssl_util.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/aead.h>
namespace crypto {
namespace nearby::crypto {
Aead::Aead(AeadAlgorithm algorithm) {
EnsureOpenSSLInit();
@@ -187,4 +186,4 @@ bool Aead::Open(absl::Span<const uint8_t> plaintext,
return true;
}
} // namespace crypto
} // namespace nearby::crypto
+4 -5
View File
@@ -26,10 +26,9 @@
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
#include <openssl/base.h>
struct evp_aead_st;
namespace crypto {
namespace nearby::crypto {
// This class exposes the AES-128-CTR-HMAC-SHA256 and AES_256_GCM AEAD. Note
// that there are two versions of most methods: an historical version based
@@ -87,9 +86,9 @@ class CRYPTO_EXPORT Aead {
size_t* output_length, size_t max_output_length) const;
absl::optional<absl::Span<const uint8_t>> key_;
const evp_aead_st* aead_;
const EVP_AEAD* aead_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_AEAD_H_
+2
View File
@@ -20,6 +20,7 @@
#include "gtest/gtest.h"
namespace nearby {
namespace {
const crypto::Aead::AeadAlgorithm kAllAlgorithms[]{
@@ -98,3 +99,4 @@ TEST_P(AeadTest, SealOpenWrongKey) {
}
} // namespace
} // namespace nearby
+2 -2
View File
@@ -40,7 +40,7 @@
#include <openssl/mem.h>
#include <openssl/pkcs8.h>
namespace crypto {
namespace nearby::crypto {
ECPrivateKey::~ECPrivateKey() = default;
@@ -186,4 +186,4 @@ bool ECPrivateKey::ExportRawPublicKey(std::string* output) const {
ECPrivateKey::ECPrivateKey() = default;
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -26,7 +26,7 @@
#include "internal/crypto_cros/crypto_export.h"
#include <openssl/base.h>
namespace crypto {
namespace nearby::crypto {
// Encapsulates an elliptic curve (EC) private key. Can be used to generate new
// keys, export keys to other formats, or to extract a public key.
@@ -91,6 +91,6 @@ class CRYPTO_EXPORT ECPrivateKey {
bssl::UniquePtr<EVP_PKEY> key_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_EC_PRIVATE_KEY_H_
@@ -23,6 +23,7 @@
#include "gtest/gtest.h"
namespace nearby {
namespace {
void ExpectKeysEqual(const crypto::ECPrivateKey* keypair1,
@@ -331,3 +332,5 @@ TEST(ECPrivateKeyUnitTest, LoadOldOpenSSLKeyTest) {
EXPECT_TRUE(keypair_openssl);
}
} // namespace nearby
+2 -2
View File
@@ -18,7 +18,7 @@
#include "internal/crypto_cros/ec_signature_creator_impl.h"
namespace crypto {
namespace nearby::crypto {
// static
std::unique_ptr<ECSignatureCreator> ECSignatureCreator::Create(
@@ -26,4 +26,4 @@ std::unique_ptr<ECSignatureCreator> ECSignatureCreator::Create(
return std::make_unique<ECSignatureCreatorImpl>(key);
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -24,7 +24,7 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
class ECPrivateKey;
class ECSignatureCreator;
@@ -60,6 +60,6 @@ class CRYPTO_EXPORT ECSignatureCreator {
std::vector<uint8_t>* out_raw_sig) = 0;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_EC_SIGNATURE_CREATOR_H_
@@ -27,7 +27,7 @@
#include <openssl/evp.h>
#include <openssl/sha.h>
namespace crypto {
namespace nearby::crypto {
ECSignatureCreatorImpl::ECSignatureCreatorImpl(ECPrivateKey* key) : key_(key) {
EnsureOpenSSLInit();
@@ -80,4 +80,4 @@ bool ECSignatureCreatorImpl::DecodeSignature(
return true;
}
} // namespace crypto
} // namespace nearby::crypto
@@ -22,7 +22,7 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/ec_signature_creator.h"
namespace crypto {
namespace nearby::crypto {
class ECSignatureCreatorImpl : public ECSignatureCreator {
public:
@@ -43,6 +43,6 @@ class ECSignatureCreatorImpl : public ECSignatureCreator {
ECPrivateKey* key_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_EC_SIGNATURE_CREATOR_IMPL_H_
@@ -26,6 +26,8 @@
#include "internal/crypto_cros/nearby_base.h"
#include "internal/crypto_cros/signature_verifier.h"
namespace nearby {
TEST(ECSignatureCreatorTest, BasicTest) {
// Do a verify round trip.
std::unique_ptr<crypto::ECPrivateKey> key_original(
@@ -59,3 +61,5 @@ TEST(ECSignatureCreatorTest, BasicTest) {
verifier.VerifyUpdate(nearbybase::as_bytes(absl::MakeSpan(data)));
ASSERT_TRUE(verifier.VerifyFinal());
}
} // namespace nearby
+3 -5
View File
@@ -28,11 +28,9 @@
#include "internal/platform/logging.h"
#else
#include "absl/log/check.h" // nogncheck
#endif
#ifndef NEARBY_SWIFTPM
#include "absl/log/log.h" // nogncheck
#endif
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "internal/crypto_cros/nearby_base.h"
@@ -41,7 +39,7 @@
#include <openssl/aes.h>
#include <openssl/evp.h>
namespace crypto {
namespace nearby::crypto {
namespace {
@@ -225,4 +223,4 @@ absl::optional<size_t> Encryptor::CryptCTR(bool do_encrypt,
return input.size();
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -28,7 +28,7 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
class SymmetricKey;
@@ -105,6 +105,6 @@ class CRYPTO_EXPORT Encryptor {
std::vector<uint8_t> iv_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_ENCRYPTOR_H_
@@ -27,6 +27,8 @@
#include "internal/crypto_cros/nearby_base.h"
#include "internal/crypto_cros/symmetric_key.h"
namespace nearby {
TEST(EncryptorTest, EncryptDecrypt) {
std::unique_ptr<crypto::SymmetricKey> key(
crypto::SymmetricKey::DeriveKeyFromPasswordUsingPbkdf2(
@@ -570,3 +572,5 @@ TEST(EncryptorTest, CipherTextNotMultipleOfBlockSize) {
EXPECT_FALSE(
encryptor.Decrypt(absl::string_view(ciphertext.get(), 1), &plaintext));
}
} // namespace nearby
+2 -2
View File
@@ -34,7 +34,7 @@
#include "internal/crypto_cros/hmac.h"
#include <openssl/digest.h>
namespace crypto {
namespace nearby::crypto {
std::string HkdfSha256(absl::string_view secret, absl::string_view salt,
absl::string_view info, size_t derived_key_size) {
@@ -62,4 +62,4 @@ std::vector<uint8_t> HkdfSha256(absl::Span<const uint8_t> secret,
return ret;
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -24,7 +24,7 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
CRYPTO_EXPORT
std::string HkdfSha256(absl::string_view secret, absl::string_view salt,
@@ -36,6 +36,6 @@ std::vector<uint8_t> HkdfSha256(absl::Span<const uint8_t> secret,
absl::Span<const uint8_t> info,
size_t derived_key_size);
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_HKDF_H_
+2 -2
View File
@@ -33,7 +33,7 @@
#include "internal/crypto_cros/secure_util.h"
#include "internal/crypto_cros/symmetric_key.h"
namespace crypto {
namespace nearby::crypto {
HMAC::HMAC(HashAlgorithm hash_alg) : hash_alg_(hash_alg), initialized_(false) {
// Only SHA-1 and SHA-256 hash algorithms are supported now.
@@ -118,4 +118,4 @@ bool HMAC::VerifyTruncated(absl::Span<const uint8_t> data,
return SecureMemEqual(digest.data(), computed_digest, digest.size());
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -31,7 +31,7 @@
#include "internal/crypto_cros/crypto_export.h"
#include "internal/crypto_cros/nearby_base.h"
namespace crypto {
namespace nearby::crypto {
// Simplify the interface and reduce includes by abstracting out the internals.
class SymmetricKey;
@@ -120,6 +120,6 @@ class CRYPTO_EXPORT HMAC {
std::vector<unsigned char> key_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_HMAC_H_
+4
View File
@@ -26,6 +26,8 @@
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
namespace nearby {
static const size_t kSHA1DigestSize = 20;
static const size_t kSHA256DigestSize = 32;
@@ -376,3 +378,5 @@ TEST(HMACTest, Bytes) {
EXPECT_FALSE(hmac.VerifyTruncated(
data, absl::MakeSpan(calculated_hmac, kSHA256DigestSize / 2)));
}
} // namespace nearby
+2 -2
View File
@@ -30,7 +30,7 @@
#include <openssl/crypto.h>
#include <openssl/err.h>
namespace crypto {
namespace nearby::crypto {
void EnsureOpenSSLInit() {
// CRYPTO_library_init may be safely called concurrently.
@@ -41,4 +41,4 @@ void ClearOpenSSLERRStack() {
ERR_clear_error();
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -20,7 +20,7 @@
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
// Provides a buffer of at least MIN_SIZE bytes, for use when calling OpenSSL's
// SHA256, HMAC, etc functions, adapting the buffer sizing rules to meet those
@@ -98,6 +98,6 @@ class OpenSSLErrStackTracer {
~OpenSSLErrStackTracer() { ClearOpenSSLERRStack(); }
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_OPENSSL_UTIL_H_
-42
View File
@@ -1,42 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*** WARNING!!! Do not add more functions and Data types to this file. ***
// This file needs to be in sync with:
// https://source.chromium.org/chromium/chromium/src/+/main:crypto/random.h
#ifndef THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_RANDOM_H_
#define THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_RANDOM_H_
#include <stddef.h>
#include <cstdint>
#include <string>
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
// Fills the given buffer with |length| random bytes of cryptographically
// secure random numbers.
// |length| must be positive.
CRYPTO_EXPORT void RandBytes(void *bytes, size_t length);
// Fills |bytes| with cryptographically-secure random bits.
CRYPTO_EXPORT void RandBytes(absl::Span<uint8_t> bytes);
} // namespace crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_RANDOM_H_
-68
View File
@@ -1,68 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/crypto_cros/random.h"
#include <stddef.h>
#include <string>
#include "gtest/gtest.h"
#include "internal/crypto_cros/nearby_base.h"
#include "internal/platform/implementation/crypto.h"
// Basic functionality tests. Does NOT test the security of the random data.
namespace crypto {
namespace {
// Ensures we don't have all trivial data, i.e. that the data is indeed random.
// Currently, that means the bytes cannot be all the same (e.g. all zeros).
bool IsTrivial(const std::string& bytes) {
for (size_t i = 0; i < bytes.size(); i++) {
if (bytes[i] != bytes[0]) {
return false;
}
}
return true;
}
TEST(RandBytes, RandBytes) {
std::string bytes(16, '\0');
RandBytes(nearbybase::WriteInto(&bytes, bytes.size()), bytes.size());
EXPECT_TRUE(!IsTrivial(bytes));
}
TEST(RandBytes, RandomString) {
constexpr size_t kSize = 30;
std::string bytes(kSize, 0);
RandBytes(const_cast<std::string::value_type*>(bytes.data()), bytes.size());
EXPECT_EQ(bytes.size(), kSize);
EXPECT_TRUE(!IsTrivial(bytes));
}
TEST(RandBytes, RandData) {
uint64_t x = nearby::RandData<uint64_t>();
uint64_t y = nearby::RandData<uint64_t>();
// Once in a billion years, consecutively generated random numbers will be
// the same and the test will fail.
EXPECT_NE(x, y);
EXPECT_NE(x >> 32, x & 0xFFFFFFFF);
}
} // namespace
} // namespace crypto
+2 -2
View File
@@ -36,7 +36,7 @@
#include <openssl/mem.h>
#include <openssl/rsa.h>
namespace crypto {
namespace nearby::crypto {
// static
std::unique_ptr<RSAPrivateKey> RSAPrivateKey::Create(uint16_t num_bits) {
@@ -126,4 +126,4 @@ bool RSAPrivateKey::ExportPublicKey(std::vector<uint8_t>* output) const {
return true;
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -25,7 +25,7 @@
#include "internal/crypto_cros/crypto_export.h"
#include <openssl/base.h>
namespace crypto {
namespace nearby::crypto {
// Encapsulates an RSA private key. Can be used to generate new keys, export
// keys to other formats, or to extract a public key.
@@ -69,6 +69,6 @@ class CRYPTO_EXPORT RSAPrivateKey {
bssl::UniquePtr<EVP_PKEY> key_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_RSA_PRIVATE_KEY_H_
@@ -21,6 +21,7 @@
#include "gtest/gtest.h"
namespace nearby {
namespace {
const uint8_t kTestPrivateKeyInfo[] = {
@@ -364,7 +365,7 @@ TEST(RSAPrivateKeyUnitTest, ShortIntegers) {
TEST(RSAPrivateKeyUnitTest, CreateFromKeyTest) {
std::unique_ptr<crypto::RSAPrivateKey> key_pair(
crypto::RSAPrivateKey::Create(512));
crypto::RSAPrivateKey::Create(2048));
ASSERT_TRUE(key_pair.get());
std::unique_ptr<crypto::RSAPrivateKey> key_copy(
@@ -384,3 +385,5 @@ TEST(RSAPrivateKeyUnitTest, CreateFromKeyTest) {
ASSERT_EQ(privkey, privkey_copy);
ASSERT_EQ(pubkey, pubkey_copy);
}
} // namespace nearby
+2 -2
View File
@@ -22,7 +22,7 @@
#include <openssl/mem.h>
#include <openssl/sha.h>
namespace crypto {
namespace nearby::crypto {
namespace {
@@ -73,4 +73,4 @@ std::unique_ptr<SecureHash> SecureHash::Create(Algorithm algorithm) {
}
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -21,7 +21,7 @@
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
// A wrapper to calculate secure hashes incrementally, allowing to
// be used when the full input is not known in advance. The end result will the
@@ -52,6 +52,6 @@ class CRYPTO_EXPORT SecureHash {
SecureHash() {}
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_SECURE_HASH_H_
@@ -23,6 +23,8 @@
#include "gtest/gtest.h"
#include "internal/crypto_cros/sha2.h"
namespace nearby {
TEST(SecureHashTest, TestUpdate) {
// Example B.3 from FIPS 180-2: long message.
std::string input3(500000, 'a'); // 'a' repeated half a million times
@@ -115,3 +117,5 @@ TEST(SecureHashTest, Equality) {
// The hash should be the same.
EXPECT_EQ(0, memcmp(output1, output2, crypto::kSHA256Length));
}
} // namespace nearby
+2 -2
View File
@@ -16,10 +16,10 @@
#include <openssl/mem.h>
namespace crypto {
namespace nearby::crypto {
bool SecureMemEqual(const void* s1, const void* s2, size_t n) {
return CRYPTO_memcmp(s1, s2, n) == 0;
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -19,7 +19,7 @@
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
// Performs a constant-time comparison of two strings, returning true if the
// strings are equal.
@@ -33,6 +33,6 @@ namespace crypto {
// http://groups.google.com/group/keyczar-discuss/browse_thread/thread/5571eca0948b2a13
CRYPTO_EXPORT bool SecureMemEqual(const void* s1, const void* s2, size_t n);
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_SECURE_UTIL_H_
+2 -2
View File
@@ -24,7 +24,7 @@
#include "internal/crypto_cros/secure_hash.h"
#include <openssl/sha.h>
namespace crypto {
namespace nearby::crypto {
std::array<uint8_t, kSHA256Length> SHA256Hash(absl::Span<const uint8_t> input) {
std::array<uint8_t, kSHA256Length> digest;
@@ -44,4 +44,4 @@ std::string SHA256HashString(absl::string_view str) {
return output;
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -25,7 +25,7 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
// These functions perform SHA-256 operations.
//
@@ -47,6 +47,6 @@ CRYPTO_EXPORT std::string SHA256HashString(absl::string_view str);
CRYPTO_EXPORT void SHA256HashString(absl::string_view str, void* output,
size_t len);
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_SHA2_H_
+4
View File
@@ -21,6 +21,8 @@
#include "gtest/gtest.h"
namespace nearby {
TEST(Sha256Test, Test1) {
// Example B.1 from FIPS 180-2: one-block message.
std::string input1 = "abc";
@@ -96,3 +98,5 @@ TEST(Sha256Test, Test3) {
for (size_t i = 0; i < sizeof(output_truncated3); i++)
EXPECT_EQ(expected3[i], static_cast<int>(output_truncated3[i]));
}
} // namespace nearby
+2 -2
View File
@@ -30,7 +30,7 @@
#include <openssl/evp.h>
#include <openssl/rsa.h>
namespace crypto {
namespace nearby::crypto {
struct SignatureVerifier::VerifyContext {
bssl::ScopedEVP_MD_CTX ctx;
@@ -119,4 +119,4 @@ void SignatureVerifier::Reset() {
signature_.clear();
}
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -23,7 +23,7 @@
#include "absl/types/span.h"
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
// The SignatureVerifier class verifies a signature using a bare public key
// (as opposed to a certificate).
@@ -76,6 +76,6 @@ class CRYPTO_EXPORT SignatureVerifier {
std::unique_ptr<VerifyContext> verify_context_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_SIGNATURE_VERIFIER_H_
@@ -23,6 +23,8 @@
#include "gtest/gtest.h"
#include "absl/types/span.h"
namespace nearby {
TEST(SignatureVerifierTest, BasicTest) {
// The input data in this test comes from real certificates.
//
@@ -422,3 +424,5 @@ TEST(SignatureVerifierTest, VerifyRSAPSS) {
verifier.VerifyUpdate(kPSSMessage);
EXPECT_FALSE(verifier.VerifyFinal());
}
} // namespace nearby
+2 -2
View File
@@ -35,7 +35,7 @@
#include <openssl/evp.h>
#include <openssl/rand.h>
namespace crypto {
namespace nearby::crypto {
namespace {
@@ -144,4 +144,4 @@ std::unique_ptr<SymmetricKey> SymmetricKey::Import(Algorithm algorithm,
SymmetricKey::SymmetricKey() = default;
} // namespace crypto
} // namespace nearby::crypto
+2 -2
View File
@@ -22,7 +22,7 @@
#include "internal/crypto_cros/crypto_export.h"
namespace crypto {
namespace nearby::crypto {
// Wraps a platform-specific symmetric key and allows it to be held in a
// scoped_ptr.
@@ -84,6 +84,6 @@ class CRYPTO_EXPORT SymmetricKey {
std::string key_;
};
} // namespace crypto
} // namespace nearby::crypto
#endif // THIRD_PARTY_NEARBY_INTERNAL_CRYPTO_SYMMETRIC_KEY_H_
@@ -21,6 +21,8 @@
#include "absl/strings/ascii.h"
#include "internal/crypto_cros/nearby_base.h"
namespace nearby {
TEST(SymmetricKeyTest, GenerateRandomKey) {
std::unique_ptr<crypto::SymmetricKey> key(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
@@ -260,3 +262,5 @@ INSTANTIATE_TEST_SUITE_P(All, SymmetricKeyDeriveKeyFromPasswordUsingPbkdf2Test,
INSTANTIATE_TEST_SUITE_P(All, SymmetricKeyDeriveKeyFromPasswordUsingScryptTest,
testing::ValuesIn(kTestVectorsScrypt));
} // namespace nearby
+17 -4
View File
@@ -1,4 +1,19 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
licenses(["notice"])
@@ -9,20 +24,19 @@ package(default_visibility = [
cc_library(
name = "data_manager",
hdrs = [
"data_manager.h",
"data_set.h",
"leveldb_data_set.h",
"memory_data_set.h",
],
deps = [
"//internal/platform:types",
"//third_party/leveldb:db",
"//third_party/leveldb:table",
"//third_party/leveldb:util",
"//third_party/protobuf:protobuf_lite",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/synchronization",
"@com_google_protobuf//:protobuf_lite",
],
)
@@ -42,7 +56,6 @@ cc_test(
timeout = "short",
srcs = [
"leveldb_data_set_test.cc",
"memory_data_set_test.cc",
],
shard_count = 8,
deps = [
-53
View File
@@ -1,53 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_INTERNAL_DATA_DATA_MANAGER_H_
#define THIRD_PARTY_NEARBY_INTERNAL_DATA_DATA_MANAGER_H_
#include <memory>
#include "absl/strings/string_view.h"
#include "internal/data/data_set.h"
#include "internal/data/leveldb_data_set.h"
#include "internal/data/memory_data_set.h"
namespace nearby {
namespace data {
class DataManager {
public:
enum class DataStorageType : int { kMemory = 0, kLevelDb = 1 };
explicit DataManager(DataStorageType data_storage_type)
: data_storage_type_(data_storage_type) {}
~DataManager() = default;
template <typename T>
std::unique_ptr<DataSet<T>> GetDataSet(absl::string_view path) {
if (data_storage_type_ == DataStorageType::kMemory) {
return std::make_unique<MemoryDataSet<T>>(path);
} else if (data_storage_type_ == DataStorageType::kLevelDb) {
return std::make_unique<LeveldbDataSet<T>>(path);
} else {
return nullptr;
}
}
private:
DataStorageType data_storage_type_;
};
} // namespace data
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_INTERNAL_DATA_DATA_MANAGER_H_
+7 -5
View File
@@ -15,12 +15,13 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_DATA_DATA_SET_H_
#define THIRD_PARTY_NEARBY_INTERNAL_DATA_DATA_SET_H_
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/functional/any_invocable.h"
namespace nearby {
namespace data {
@@ -43,12 +44,13 @@ class DataSet {
// Asynchronously initializes the object, which must have been created by the
// DataManager::GetDataSet<T> function. |callback| will be invoked on the
// calling thread when complete.
virtual void Initialize(std::function<void(InitStatus)> callback) = 0;
virtual void Initialize(absl::AnyInvocable<void(InitStatus) &&> callback) = 0;
// Asynchronously loads all entries from the database and invokes |callback|
// when complete.
virtual void LoadEntries(
std::function<void(bool, std::unique_ptr<std::vector<T>>)> callback) = 0;
absl::AnyInvocable<void(bool, std::unique_ptr<std::vector<T>>) &&>
callback) = 0;
// Asynchronously saves |entries_to_save| and deletes entries from
// |keys_to_remove| from the database. |callback| will be invoked on the
@@ -57,11 +59,11 @@ class DataSet {
virtual void UpdateEntries(
std::unique_ptr<KeyEntryVector> entries_to_save,
std::unique_ptr<std::vector<std::string>> keys_to_remove,
std::function<void(bool)> callback) = 0;
absl::AnyInvocable<void(bool) &&> callback) = 0;
// Asynchronously destroys the database. Use this call only if the database
// needs to be destroyed for this particular profile.
virtual void Destroy(std::function<void(bool)> callback) = 0;
virtual void Destroy(absl::AnyInvocable<void(bool) &&> callback) = 0;
};
} // namespace data
+18 -16
View File
@@ -15,14 +15,13 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_DATA_LEVELDB_DATA_SET_H_
#define THIRD_PARTY_NEARBY_INTERNAL_DATA_LEVELDB_DATA_SET_H_
#include <functional>
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/functional/any_invocable.h"
#include "absl/strings/string_view.h"
#include "third_party/leveldb/include/db.h"
#include "third_party/leveldb/include/iterator.h"
@@ -31,7 +30,7 @@
#include "third_party/leveldb/include/status.h"
#include "internal/data/data_set.h"
#include "internal/platform/logging.h"
#include "third_party/protobuf/message_lite.h"
#include "google/protobuf/message_lite.h"
namespace nearby {
namespace data {
@@ -47,17 +46,19 @@ class LeveldbDataSet : public DataSet<T> {
explicit LeveldbDataSet(absl::string_view path) : path_(path) {}
~LeveldbDataSet() override = default;
void Initialize(std::function<void(InitStatus)> callback) override;
void LoadEntries(std::function<void(bool, std::unique_ptr<std::vector<T>>)>
callback) override;
void Initialize(absl::AnyInvocable<void(InitStatus) &&> callback) override;
void LoadEntries(
absl::AnyInvocable<void(bool, std::unique_ptr<std::vector<T>>) &&>
callback) override;
void LoadEntriesWithKeys(
std::function<
void(bool, std::unique_ptr<std::vector<std::pair<std::string, T>>>)>
absl::AnyInvocable<
void(bool,
std::unique_ptr<std::vector<std::pair<std::string, T>>>) &&>
callback);
void UpdateEntries(std::unique_ptr<KeyEntryVector> entries_to_save,
std::unique_ptr<std::vector<std::string>> keys_to_remove,
std::function<void(bool)> callback) override;
void Destroy(std::function<void(bool)> callback) override;
absl::AnyInvocable<void(bool) &&> callback) override;
void Destroy(absl::AnyInvocable<void(bool) &&> callback) override;
private:
void Serialize(T const& value, std::string& str);
@@ -73,7 +74,7 @@ template <typename T,
std::enable_if_t<std::is_base_of<proto2::MessageLite, T>::value, bool>
isMessageLite>
void LeveldbDataSet<T, isMessageLite>::Initialize(
std::function<void(InitStatus)> callback) {
absl::AnyInvocable<void(InitStatus) &&> callback) {
leveldb::Options options;
options.create_if_missing = true;
@@ -99,7 +100,8 @@ template <typename T,
std::enable_if_t<std::is_base_of<proto2::MessageLite, T>::value, bool>
isMessageLite>
void LeveldbDataSet<T, isMessageLite>::LoadEntries(
std::function<void(bool, std::unique_ptr<std::vector<T>>)> callback) {
absl::AnyInvocable<void(bool, std::unique_ptr<std::vector<T>>) &&>
callback) {
auto result = std::make_unique<std::vector<T>>();
if (status_ != InitStatus::kOK) {
std::move(callback)(false, std::move(result));
@@ -130,8 +132,8 @@ template <typename T,
std::enable_if_t<std::is_base_of<proto2::MessageLite, T>::value, bool>
isMessageLite>
void LeveldbDataSet<T, isMessageLite>::LoadEntriesWithKeys(
std::function<void(bool,
std::unique_ptr<std::vector<std::pair<std::string, T>>>)>
absl::AnyInvocable<
void(bool, std::unique_ptr<std::vector<std::pair<std::string, T>>>) &&>
callback) {
auto result = std::make_unique<std::vector<std::pair<std::string, T>>>();
if (status_ != InitStatus::kOK) {
@@ -165,7 +167,7 @@ template <typename T,
void LeveldbDataSet<T, isMessageLite>::UpdateEntries(
std::unique_ptr<KeyEntryVector> entries_to_save,
std::unique_ptr<std::vector<std::string>> keys_to_remove,
std::function<void(bool)> callback) {
absl::AnyInvocable<void(bool) &&> callback) {
NEARBY_LOGS(INFO) << "UpdateEntries is called.";
if (status_ != InitStatus::kOK) {
std::move(callback)(false);
@@ -193,7 +195,7 @@ template <typename T,
std::enable_if_t<std::is_base_of<proto2::MessageLite, T>::value, bool>
isMessageLite>
void LeveldbDataSet<T, isMessageLite>::Destroy(
std::function<void(bool)> callback) {
absl::AnyInvocable<void(bool) &&> callback) {
NEARBY_LOGS(INFO) << "Destroy is called.";
db_.reset();
leveldb::DestroyDB(path_, leveldb::Options());
-106
View File
@@ -1,106 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_INTERNAL_DATA_MEMORY_DATA_SET_H_
#define THIRD_PARTY_NEARBY_INTERNAL_DATA_MEMORY_DATA_SET_H_
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/data/data_set.h"
namespace nearby {
namespace data {
template <typename T>
class MemoryDataSet : public DataSet<T> {
public:
using KeyEntryVector = std::vector<std::pair<std::string, T>>;
explicit MemoryDataSet(absl::string_view path) : path_(path) {}
~MemoryDataSet() override = default;
void Initialize(std::function<void(InitStatus)> callback) override;
void LoadEntries(std::function<void(bool, std::unique_ptr<std::vector<T>>)>
callback) override;
void UpdateEntries(std::unique_ptr<KeyEntryVector> entries_to_save,
std::unique_ptr<std::vector<std::string>> keys_to_remove,
std::function<void(bool)> callback) override;
void Destroy(std::function<void(bool)> callback) override;
private:
std::string path_;
absl::Mutex mutex_;
absl::flat_hash_map<std::string, T> entries_;
};
template <typename T>
void MemoryDataSet<T>::Initialize(std::function<void(InitStatus)> callback) {
std::move(callback)(InitStatus::kOK);
}
template <typename T>
void MemoryDataSet<T>::LoadEntries(
std::function<void(bool, std::unique_ptr<std::vector<T>>)> callback) {
auto result = std::make_unique<std::vector<T>>();
auto it = entries_.begin();
while (it != entries_.end()) {
result->push_back(it->second);
++it;
}
std::move(callback)(true, std::move(result));
}
template <typename T>
void MemoryDataSet<T>::UpdateEntries(
std::unique_ptr<KeyEntryVector> entries_to_save,
std::unique_ptr<std::vector<std::string>> keys_to_remove,
std::function<void(bool)> callback) {
if (entries_to_save != nullptr) {
auto it = entries_to_save->begin();
while (it != entries_to_save->end()) {
entries_.emplace(it->first, it->second);
++it;
}
}
if (keys_to_remove != nullptr) {
auto it = keys_to_remove->begin();
while (it != keys_to_remove->end()) {
entries_.erase(*it);
++it;
}
}
std::move(callback)(true);
}
template <typename T>
void MemoryDataSet<T>::Destroy(std::function<void(bool)> callback) {
entries_.clear();
std::move(callback)(true);
}
} // namespace data
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_INTERNAL_DATA_MEMORY_DATA_SET_H_
-71
View File
@@ -1,71 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/data/memory_data_set.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
namespace nearby {
namespace data {
namespace {
TEST(MemoryDataSet, TestUpdateEntries) {
bool result = false;
MemoryDataSet<std::string> string_set{""};
auto temp = MemoryDataSet<std::string>::KeyEntryVector(
{{"id1", "string1"}, {"id2", "string2"}});
auto data =
std::make_unique<MemoryDataSet<std::string>::KeyEntryVector>(temp);
string_set.UpdateEntries(std::move(data), nullptr,
[&result](bool res) { result = res; });
EXPECT_TRUE(result);
}
TEST(MemoryDataSet, TestLoadEntries) {
std::vector<std::string> result = {};
MemoryDataSet<std::string> string_set{""};
auto temp = MemoryDataSet<std::string>::KeyEntryVector(
{{"id1", "string1"}, {"id2", "string2"}});
auto data =
std::make_unique<MemoryDataSet<std::string>::KeyEntryVector>(temp);
string_set.UpdateEntries(std::move(data), nullptr, [](bool ans) {});
string_set.LoadEntries(
[&result](bool ans, std::unique_ptr<std::vector<std::string>> res) {
auto it = res->begin();
while (it != res->end()) {
result.push_back(*it);
++it;
}
});
EXPECT_THAT(result, testing::SizeIs(2));
std::sort(result.begin(), result.end());
EXPECT_EQ(result, std::vector<std::string>({"string1", "string2"}));
}
} // namespace
} // namespace data
} // namespace nearby
+3 -2
View File
@@ -42,11 +42,13 @@ cc_library(
],
visibility = [
"//:__subpackages__",
"//googlemac/iPhone/Shared/Identity/SmartSetup:__subpackages__",
"//location/nearby/cpp:__subpackages__",
"//location/nearby/sharing/sdk:__subpackages__",
"//location/nearby/testing:__subpackages__",
],
deps = [
":flag_reader",
"//internal/platform:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/strings",
@@ -60,7 +62,6 @@ cc_test(
deps = [
":flag_reader",
":nearby_flags",
"//internal/platform/implementation/g3",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings",
"@com_google_googletest//:gtest",
+15 -12
View File
@@ -14,10 +14,13 @@
#include "internal/flags/nearby_flags.h"
#include <cstdint>
#include <string>
#include "internal/platform/mutex.h"
#include "internal/platform/mutex_lock.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/flags/flag.h"
#include "internal/flags/flag_reader.h"
namespace nearby {
@@ -27,7 +30,7 @@ NearbyFlags& NearbyFlags::GetInstance() {
}
bool NearbyFlags::GetBoolFlag(const flags::Flag<bool>& flag) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
const auto& it = overrided_bool_flag_values_.find(flag.name());
if (it != overrided_bool_flag_values_.end()) {
@@ -41,7 +44,7 @@ bool NearbyFlags::GetBoolFlag(const flags::Flag<bool>& flag) {
}
int64_t NearbyFlags::GetInt64Flag(const flags::Flag<int64_t>& flag) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
const auto& it = overrided_int64_flag_values_.find(flag.name());
if (it != overrided_int64_flag_values_.end()) {
@@ -55,7 +58,7 @@ int64_t NearbyFlags::GetInt64Flag(const flags::Flag<int64_t>& flag) {
}
double NearbyFlags::GetDoubleFlag(const flags::Flag<double>& flag) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
const auto& it = overrided_double_flag_values_.find(flag.name());
if (it != overrided_double_flag_values_.end()) {
@@ -70,7 +73,7 @@ double NearbyFlags::GetDoubleFlag(const flags::Flag<double>& flag) {
std::string NearbyFlags::GetStringFlag(
const flags::Flag<absl::string_view>& flag) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
const auto& it = overrided_string_flag_values_.find(flag.name());
if (it != overrided_string_flag_values_.end()) {
@@ -84,36 +87,36 @@ std::string NearbyFlags::GetStringFlag(
}
void NearbyFlags::SetFlagReader(flags::FlagReader& flag_reader) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
flag_reader_ = &flag_reader;
}
void NearbyFlags::OverrideBoolFlagValue(const flags::Flag<bool>& flag,
bool new_value) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
overrided_bool_flag_values_[flag.name()] = new_value;
}
void NearbyFlags::OverrideInt64FlagValue(const flags::Flag<int64_t>& flag,
int64_t new_value) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
overrided_int64_flag_values_[flag.name()] = new_value;
}
void NearbyFlags::OverrideDoubleFlagValue(const flags::Flag<double>& flag,
double new_value) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
overrided_double_flag_values_[flag.name()] = new_value;
}
void NearbyFlags::OverrideStringFlagValue(
const flags::Flag<absl::string_view>& flag, absl::string_view new_value) {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
overrided_string_flag_values_[flag.name()] = std::string(new_value);
}
void NearbyFlags::ResetOverridedValues() {
MutexLock lock(&mutex_);
absl::MutexLock lock(&mutex_);
overrided_bool_flag_values_.clear();
overrided_int64_flag_values_.clear();
overrided_double_flag_values_.clear();
+6 -3
View File
@@ -15,13 +15,16 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_FLAGS_NEARBY_FLAGS_H_
#define THIRD_PARTY_NEARBY_INTERNAL_FLAGS_NEARBY_FLAGS_H_
#include <cstdint>
#include <string>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "internal/flags/default_flag_reader.h"
#include "internal/flags/flag.h"
#include "internal/flags/flag_reader.h"
#include "internal/platform/mutex.h"
namespace nearby {
@@ -65,7 +68,7 @@ class NearbyFlags final : public nearby::flags::FlagReader {
absl::string_view new_value)
ABSL_LOCKS_EXCLUDED(mutex_);
// Reset all overrided values.
// Reset all overridden values.
void ResetOverridedValues() ABSL_LOCKS_EXCLUDED(mutex_);
private:
@@ -74,7 +77,7 @@ class NearbyFlags final : public nearby::flags::FlagReader {
flags::FlagReader* flag_reader_ = nullptr;
flags::DefaultFlagReader default_flag_reader_;
mutable Mutex mutex_;
mutable absl::Mutex mutex_;
absl::flat_hash_map<std::string, bool> overrided_bool_flag_values_
ABSL_GUARDED_BY(mutex_);
+48
View File
@@ -1,3 +1,17 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cc_library(
name = "authentication_transport_interface",
hdrs = [
@@ -22,6 +36,7 @@ cc_library(
"//presence:__subpackages__",
],
deps = [
":authentication_status",
":authentication_transport_interface",
"//internal/platform:connection_info",
"//internal/platform:types",
@@ -29,3 +44,36 @@ cc_library(
"@com_google_absl//absl/types:variant",
],
)
cc_library(
name = "authentication_status",
hdrs = [
"authentication_status.h",
],
visibility = [
"//connections:__subpackages__",
"//presence:__subpackages__",
"//sharing:__subpackages__",
],
)
cc_library(
name = "test_support",
testonly = 1,
srcs = [
"fake_device_provider.cc",
],
hdrs = [
"fake_device_provider.h",
],
compatible_with = ["//buildenv/target:non_prod"],
visibility = [
"//presence:__subpackages__",
],
deps = [
":authentication_status",
":authentication_transport_interface",
":device",
"@com_google_absl//absl/strings:string_view",
],
)
@@ -1,4 +1,4 @@
// Copyright 2021 Google LLC
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,10 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/nsd_service_info.h"
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_AUTHENTICATION_STATUS_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_AUTHENTICATION_STATUS_H_
namespace nearby {
constexpr absl::string_view NsdServiceInfo::kNsdTypeFormat;
enum class AuthenticationStatus {
kUnknown = 0,
kSuccess = 1,
kFailure = 2,
};
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_CONNECTIONS_AUTHENTICATION_STATUS_H_
+1 -6
View File
@@ -15,17 +15,12 @@
#ifndef THIRD_PARTY_NEARBY_CONNECTIONS_DEVICE_PROVIDER_H_
#define THIRD_PARTY_NEARBY_CONNECTIONS_DEVICE_PROVIDER_H_
#include "internal/interop/authentication_status.h"
#include "internal/interop/authentication_transport.h"
#include "internal/interop/device.h"
namespace nearby {
enum class AuthenticationStatus {
kUnknown = 0,
kSuccess = 1,
kFailure = 2,
};
// The base device provider class for use with the Nearby Connections V3 APIs.
// This class currently provides a function to get the local device for whatever
// client implements it.
+40
View File
@@ -0,0 +1,40 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/interop/fake_device_provider.h"
#include "absl/strings/string_view.h"
#include "internal/interop/authentication_status.h"
#include "internal/interop/authentication_transport.h"
#include "internal/interop/device.h"
namespace nearby {
FakeDeviceProvider::FakeDeviceProvider() = default;
const NearbyDevice* FakeDeviceProvider::GetLocalDevice() { return nullptr; }
AuthenticationStatus FakeDeviceProvider::AuthenticateAsInitiator(
const NearbyDevice& remote_device, absl::string_view shared_secret,
const AuthenticationTransport& authentication_transport) const {
return AuthenticationStatus::kSuccess;
}
AuthenticationStatus FakeDeviceProvider::AuthenticateAsResponder(
absl::string_view shared_secret,
const AuthenticationTransport& authentication_transport) const {
return AuthenticationStatus::kSuccess;
}
} // namespace nearby
+45
View File
@@ -0,0 +1,45 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_PRESENCE_FAKE_DEVICE_PROVIDER_H_
#define THIRD_PARTY_NEARBY_PRESENCE_FAKE_DEVICE_PROVIDER_H_
#include "absl/strings/string_view.h"
#include "internal/interop/authentication_status.h"
#include "internal/interop/authentication_transport.h"
#include "internal/interop/device.h"
#include "internal/interop/device_provider.h"
namespace nearby {
class FakeDeviceProvider : public NearbyDeviceProvider {
public:
FakeDeviceProvider();
FakeDeviceProvider(const FakeDeviceProvider&) = delete;
FakeDeviceProvider& operator=(const FakeDeviceProvider&) = delete;
const NearbyDevice* GetLocalDevice() override;
AuthenticationStatus AuthenticateAsInitiator(
const NearbyDevice& remote_device, absl::string_view shared_secret,
const AuthenticationTransport& authentication_transport) const override;
AuthenticationStatus AuthenticateAsResponder(
absl::string_view shared_secret,
const AuthenticationTransport& authentication_transport) const override;
};
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_PRESENCE_FAKE_DEVICE_PROVIDER_H_
+54 -18
View File
@@ -1,21 +1,26 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
licenses(["notice"])
cc_library(
name = "types",
name = "url",
srcs = [
"http_request.cc",
"http_response.cc",
"http_status_code.cc",
"url.cc",
"utils.cc",
],
hdrs = [
"http_body.h",
"http_client.h",
"http_client_factory.h",
"http_request.h",
"http_response.h",
"http_status_code.h",
"url.h",
"utils.h",
],
@@ -24,11 +29,43 @@ cc_library(
"//internal:__pkg__",
"//internal:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
],
)
cc_library(
name = "types",
srcs = [
"http_request.cc",
"http_response.cc",
"http_status_code.cc",
],
hdrs = [
"http_body.h",
"http_client.h",
"http_client_factory.h",
"http_request.h",
"http_response.h",
"http_status_code.h",
],
visibility = [
"//fastpair:__subpackages__",
"//internal:__pkg__",
"//internal:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
":url",
"//internal/platform:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
@@ -50,19 +87,17 @@ cc_library(
"//fastpair:__subpackages__",
"//internal:__pkg__",
"//internal:__subpackages__",
"//location/nearby/cpp/sharing:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
":types",
"//internal/platform:types",
"//internal/platform/implementation:platform",
"//internal/platform/implementation:comm",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/strings",
],
)
@@ -82,9 +117,10 @@ cc_test(
deps = [
":nearby_http_client",
":types",
":url",
"//internal/platform/implementation:comm",
"//internal/platform/implementation:platform",
"//internal/platform/implementation/g3",
"//internal/platform/implementation/g3", # fixdeps: keep
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/status",
+8 -3
View File
@@ -15,12 +15,15 @@
#ifndef THIRD_PARTY_NEARBY_INTERNAL_NETWORK_HTTP_CLIENT_H_
#define THIRD_PARTY_NEARBY_INTERNAL_NETWORK_HTTP_CLIENT_H_
#include <functional>
#include <memory>
#include "absl/base/thread_annotations.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "internal/network/http_request.h"
#include "internal/network/http_response.h"
#include "internal/platform/mutex.h"
#include "internal/platform/mutex_lock.h"
namespace nearby {
@@ -60,12 +63,14 @@ class HttpClient {
// Starts HTTP request in asynchronization mode.
virtual void StartRequest(
const HttpRequest& request,
std::function<void(const absl::StatusOr<HttpResponse>&)> callback) = 0;
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)>
callback) = 0;
// Starts cancellable request in asynchronization mode.
virtual void StartCancellableRequest(
std::unique_ptr<CancellableRequest> request,
std::function<void(const absl::StatusOr<HttpResponse>&)> callback) = 0;
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)>
callback) = 0;
// Gets HTTP response in synchronization mode.
virtual absl::StatusOr<HttpResponse> GetResponse(
+13 -7
View File
@@ -14,14 +14,20 @@
#include "internal/network/http_client_impl.h"
#include <functional>
#include <memory>
#include <ostream>
#include <sstream>
#include <utility>
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "internal/network/debug.h"
#include "internal/network/http_request.h"
#include "internal/network/http_response.h"
#include "internal/network/http_status_code.h"
#include "internal/platform/implementation/http_loader.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h"
#include "internal/platform/single_thread_executor.h"
@@ -31,10 +37,10 @@ namespace network {
void NearbyHttpClient::StartRequest(
const HttpRequest& request,
std::function<void(const absl::StatusOr<HttpResponse>&)> callback) {
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)> callback) {
MutexLock lock(&mutex_);
executor_.Execute(
[request = std::move(request), callback = std::move(callback)]() {
[request = std::move(request), callback = std::move(callback)]() mutable {
NEARBY_LOGS(INFO) << __func__ << ": Start async request to url="
<< request.GetUrl().GetUrlPath();
absl::StatusOr<HttpResponse> response = InternalGetResponse(request);
@@ -58,7 +64,7 @@ void NearbyHttpClient::StartRequest(
void NearbyHttpClient::StartCancellableRequest(
std::unique_ptr<CancellableRequest> cancellable_request,
std::function<void(const absl::StatusOr<HttpResponse>&)> callback) {
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)> callback) {
MutexLock lock(&mutex_);
if (cancellable_request == nullptr) {
NEARBY_LOGS(ERROR) << __func__ << ": invalid cancellable request.";
@@ -68,7 +74,7 @@ void NearbyHttpClient::StartCancellableRequest(
executor_
.Execute(
[cancellable_request = std::move(cancellable_request),
callback = std::move(callback)]() {
callback = std::move(callback)]() mutable {
NEARBY_LOGS(INFO)
<< __func__ << ": Start async request to url="
<< cancellable_request->http_request().GetUrl().GetUrlPath();
@@ -149,7 +155,7 @@ absl::StatusOr<HttpResponse> NearbyHttpClient::InternalGetResponse(
request_stream << std::endl;
request_stream << "body size: " << request.GetBody().GetRawData().size()
<< std::endl;
NEARBY_LOGS(VERBOSE) << request_stream.str();
NEARBY_VLOG(1) << request_stream.str();
}
absl::StatusOr<api::WebResponse> web_response =
@@ -170,7 +176,7 @@ absl::StatusOr<HttpResponse> NearbyHttpClient::InternalGetResponse(
}
response_stream << std::endl;
response_stream << "body size: " << web_response->body.size() << std::endl;
NEARBY_LOGS(VERBOSE) << response_stream.str();
NEARBY_VLOG(1) << response_stream.str();
}
HttpResponse response;
+5 -4
View File
@@ -37,13 +37,14 @@ class NearbyHttpClient : public HttpClient {
NearbyHttpClient(NearbyHttpClient&&) = default;
NearbyHttpClient& operator=(NearbyHttpClient&&) = default;
void StartRequest(const HttpRequest& request,
std::function<void(const absl::StatusOr<HttpResponse>&)>
callback) override ABSL_LOCKS_EXCLUDED(mutex_);
void StartRequest(
const HttpRequest& request,
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)> callback)
override ABSL_LOCKS_EXCLUDED(mutex_);
void StartCancellableRequest(
std::unique_ptr<CancellableRequest> request,
std::function<void(const absl::StatusOr<HttpResponse>&)> callback)
absl::AnyInvocable<void(const absl::StatusOr<HttpResponse>&)> callback)
override ABSL_LOCKS_EXCLUDED(mutex_);
// Gets HTTP response in synchronization mode.
+264 -200
View File
@@ -16,13 +16,27 @@
licenses(["notice"])
cc_library(
name = "logging",
hdrs = [
"logging.h",
],
visibility = [
"//:__subpackages__",
],
deps = [
"@com_google_absl//absl/log",
"@com_google_absl//absl/log:check",
"@com_google_absl//absl/log:globals",
],
)
cc_library(
name = "base",
srcs = [
"base64_utils.cc",
"bluetooth_utils.cc",
"input_stream.cc",
"nsd_service_info.cc",
"prng.cc",
],
hdrs = [
@@ -46,20 +60,14 @@ cc_library(
],
copts = ["-DCORE_ADAPTER_DLL"],
visibility = [
"//connections:__subpackages__",
"//fastpair:__subpackages__",
"//internal/auth:__subpackages__",
"//internal/platform:__subpackages__",
"//internal/platform/implementation:__subpackages__",
"//internal/preferences:__subpackages__",
"//internal/weave:__subpackages__",
"//location/nearby/cpp:__subpackages__",
"//presence:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
"//:__subpackages__",
"//chrome/chromeos/assistant/data_migration/lib:__pkg__",
],
deps = [
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/container:flat_hash_set",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/meta:type_traits",
"@com_google_absl//absl/strings",
@@ -77,7 +85,6 @@ cc_library(
],
hdrs = [
"base_input_stream.h",
"base_mutex_lock.h",
"byte_utils.h",
],
visibility = [
@@ -86,7 +93,6 @@ cc_library(
],
deps = [
":base",
"//internal/platform/implementation:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/strings:str_format",
],
@@ -113,37 +119,6 @@ cc_library(
],
)
cc_library(
name = "connection_info",
srcs = [
"ble_connection_info.cc",
"bluetooth_connection_info.cc",
"connection_info.cc",
"wifi_lan_connection_info.cc",
],
hdrs = [
"ble_connection_info.h",
"bluetooth_connection_info.h",
"connection_info.h",
"wifi_lan_connection_info.h",
],
visibility = [
"//connections/implementation:__pkg__",
"//connections/v3:__pkg__",
"//internal/interop:__pkg__",
"//presence:__subpackages__",
],
deps = [
":types",
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/types:variant",
],
)
cc_library(
name = "error_code_recorder",
srcs = [
@@ -155,7 +130,7 @@ cc_library(
],
visibility = ["//connections/implementation:__subpackages__"],
deps = [
":types",
":logging",
"//proto:connections_enums_cc_proto",
"//proto/errorcode:error_code_enums_cc_proto",
"@com_google_absl//absl/functional:any_invocable",
@@ -177,11 +152,196 @@ cc_library(
"//presence:__subpackages__",
],
deps = [
"//internal/platform/implementation:types",
":base",
"@boringssl//:crypto",
"@com_google_absl//absl/strings",
],
)
cc_library(
name = "connection_info",
srcs = [
"ble_connection_info.cc",
"bluetooth_connection_info.cc",
"connection_info.cc",
"wifi_lan_connection_info.cc",
],
hdrs = [
"ble_connection_info.h",
"bluetooth_connection_info.h",
"connection_info.h",
"wifi_lan_connection_info.h",
],
visibility = [
"//connections/implementation:__pkg__",
"//connections/v3:__pkg__",
"//internal/interop:__pkg__",
"//presence:__subpackages__",
],
deps = [
":logging",
"//proto:connections_enums_cc_proto",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/types:variant",
],
)
cc_library(
name = "types",
srcs = [
"blocking_queue_stream.cc",
"clock_impl.cc",
"device_info_impl.cc",
"monitored_runnable.cc",
"pending_job_registry.cc",
"pipe.cc",
"task_runner_impl.cc",
"timer_impl.cc",
],
hdrs = [
"array_blocking_queue.h",
"atomic_boolean.h",
"atomic_reference.h",
"blocking_queue_stream.h",
"borrowable.h",
"cancelable.h",
"cancelable_alarm.h",
"cancellable_task.h",
"clock.h",
"clock_impl.h",
"condition_variable.h",
"count_down_latch.h",
"crypto.h",
"device_info.h",
"device_info_impl.h",
"direct_executor.h",
"file.h",
"future.h",
"lockable.h",
"logging.h",
"monitored_runnable.h",
"multi_thread_executor.h",
"mutex.h",
"mutex_lock.h",
"pending_job_registry.h",
"pipe.h",
"scheduled_executor.h",
"settable_future.h",
"single_thread_executor.h",
"submittable_executor.h",
"system_clock.h",
"task_runner.h",
"task_runner_impl.h",
"thread_check_callable.h",
"thread_check_runnable.h",
"timer.h",
"timer_impl.h",
],
visibility = [
"//connections:__subpackages__",
"//fastpair:__subpackages__",
"//internal/account:__subpackages__",
"//internal/auth:__subpackages__",
"//internal/auth/credential_store:__subpackages__",
"//internal/base:__subpackages__",
"//internal/crypto:__subpackages__",
"//internal/data:__subpackages__",
"//internal/flags:__subpackages__",
"//internal/interop:__pkg__",
"//internal/network:__subpackages__",
"//internal/platform:__subpackages__",
"//internal/platform/implementation/g3:__pkg__",
"//internal/platform/implementation/windows:__subpackages__",
"//internal/preferences:__subpackages__",
"//internal/proto/analytics:__subpackages__",
"//internal/test:__subpackages__",
"//internal/weave:__subpackages__",
"//location/nearby/apps:__subpackages__",
"//location/nearby/cpp:__subpackages__",
"//location/nearby/sharing/sdk:__subpackages__",
"//location/nearby/testing/nearby_native:__subpackages__",
"//presence:__subpackages__",
"//sharing:__subpackages__",
],
deps = [
":base",
":util",
"//internal/base:files",
"//internal/crypto_cros",
"//internal/flags:nearby_flags",
"//internal/platform/flags:platform_flags",
"//internal/platform/implementation:platform",
"//internal/platform/implementation:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/log",
"@com_google_absl//absl/log:check",
"@com_google_absl//absl/log:globals",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_absl//absl/types:span",
],
)
cc_library(
name = "comm",
srcs = [
"ble.cc",
"ble_v2.cc",
"bluetooth_classic.cc",
"credential_storage_impl.cc",
"file.cc",
"wifi_direct.cc",
"wifi_hotspot.cc",
"wifi_lan.cc",
],
hdrs = [
"ble.h",
"ble_v2.h",
"bluetooth_adapter.h",
"bluetooth_classic.h",
"credential_storage_impl.h",
"webrtc.h",
"wifi.h",
"wifi_direct.h",
"wifi_hotspot.h",
"wifi_lan.h",
],
copts = [
"-DCORE_ADAPTER_DLL",
"-DNO_WEBRTC",
],
visibility = [
"//connections:__subpackages__",
"//fastpair:__subpackages__",
"//internal/platform/implementation:__subpackages__",
"//internal/test:__subpackages__",
"//presence:__subpackages__",
],
deps = [
":base",
":cancellation_flag",
":types",
":uuid",
"//internal/base",
"//internal/platform/implementation:comm",
"//internal/platform/implementation:platform",
"//internal/platform/implementation:wifi_utils",
# TODO: Support WebRTC
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/status",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:optional",
],
)
cc_library(
name = "test_util",
testonly = True,
@@ -196,7 +356,6 @@ cc_library(
"//fastpair:__subpackages__",
"//internal/platform/implementation:__subpackages__",
"//presence:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
],
deps = [
":base",
@@ -205,10 +364,13 @@ cc_library(
"//internal/base",
"//internal/platform/implementation:comm",
"//internal/test",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/container:flat_hash_set",
"@com_google_absl//absl/status",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/time",
"@com_google_absl//absl/types:optional",
],
)
@@ -275,150 +437,55 @@ cc_test(
],
)
cc_library(
name = "types",
cc_test(
name = "public_device_test",
size = "small",
timeout = "moderate",
srcs = [
"clock_impl.cc",
"device_info_impl.cc",
"monitored_runnable.cc",
"pending_job_registry.cc",
"pipe.cc",
"task_runner_impl.cc",
"timer_impl.cc",
],
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"borrowable.h",
"cancelable.h",
"cancelable_alarm.h",
"cancellable_task.h",
"clock.h",
"clock_impl.h",
"condition_variable.h",
"count_down_latch.h",
"crypto.h",
"device_info.h",
"device_info_impl.h",
"direct_executor.h",
"file.h",
"future.h",
"lockable.h",
"logging.h",
"monitored_runnable.h",
"multi_thread_executor.h",
"mutex.h",
"mutex_lock.h",
"pending_job_registry.h",
"pipe.h",
"scheduled_executor.h",
"settable_future.h",
"single_thread_executor.h",
"submittable_executor.h",
"system_clock.h",
"task_runner.h",
"task_runner_impl.h",
"thread_check_callable.h",
"thread_check_runnable.h",
"timer.h",
"timer_impl.h",
],
visibility = [
"//connections:__subpackages__",
"//fastpair:__subpackages__",
"//internal/account:__subpackages__",
"//internal/auth:__subpackages__",
"//internal/auth/credential_store:__subpackages__",
"//internal/base:__subpackages__",
"//internal/data:__subpackages__",
"//internal/flags:__subpackages__",
"//internal/interop:__pkg__",
"//internal/network:__subpackages__",
"//internal/platform:__subpackages__",
"//internal/platform/implementation/g3:__pkg__",
"//internal/platform/implementation/linux:__subpackages__",
"//internal/platform/implementation/windows:__subpackages__",
"//internal/preferences:__subpackages__",
"//internal/proto/analytics:__subpackages__",
"//internal/test:__subpackages__",
"//internal/weave:__subpackages__",
"//location/nearby/analytics/cpp:__subpackages__",
"//location/nearby/apps:__subpackages__",
"//location/nearby/cpp:__subpackages__",
"//location/nearby/testing/nearby_native:__subpackages__",
"//presence:__subpackages__",
"//third_party/nearby/sharing:__subpackages__",
],
deps = [
":base",
":util",
"//internal/crypto_cros",
"//internal/platform/implementation:platform",
"//internal/platform/implementation:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/functional:any_invocable",
"@com_google_absl//absl/log:check",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_glog//:glog",
],
)
cc_library(
name = "comm",
srcs = [
"ble.cc",
"ble_v2.cc",
"bluetooth_classic.cc",
"credential_storage_impl.cc",
"file.cc",
"wifi_direct.cc",
"wifi_hotspot.cc",
"wifi_lan.cc",
"wifi_utils.cc",
],
hdrs = [
"ble.h",
"ble_v2.h",
"bluetooth_adapter.h",
"bluetooth_classic.h",
"credential_storage_impl.h",
"webrtc.h",
"wifi.h",
"wifi_direct.h",
"wifi_hotspot.h",
"wifi_lan.h",
"wifi_utils.h",
],
copts = [
"-DCORE_ADAPTER_DLL",
"-DNO_WEBRTC",
],
visibility = [
"//connections:__subpackages__",
"//fastpair:__subpackages__",
"//internal/platform/implementation:__subpackages__",
"//internal/test:__subpackages__",
"//presence:__subpackages__",
"ble_connection_info_test.cc",
"ble_test.cc",
"ble_v2_test.cc",
"bluetooth_adapter_test.cc",
"bluetooth_classic_test.cc",
"bluetooth_connection_info_test.cc",
"pipe_test.cc",
"wifi_direct_test.cc",
"wifi_hotspot_test.cc",
"wifi_lan_connection_info_test.cc",
"wifi_lan_test.cc",
"wifi_test.cc",
],
deps = [
":base",
":cancellation_flag",
":comm",
":connection_info",
":test_util",
":types",
":uuid",
"//internal/base",
"//internal/platform/implementation:comm",
"//internal/platform/implementation:platform",
# TODO: Support WebRTC
"@com_google_absl//absl/container:flat_hash_map",
"@com_google_absl//absl/container:flat_hash_set",
"@com_google_absl//absl/functional:any_invocable",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/status",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/strings:str_format",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/time",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "credential_storage_impl_test",
srcs = ["credential_storage_impl_test.cc"],
deps = [
":comm",
"//internal/platform/implementation:comm",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/proto:credential_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings:string_view",
"@com_google_googletest//:gtest_main",
],
)
@@ -429,38 +496,22 @@ cc_test(
srcs = [
"atomic_boolean_test.cc",
"atomic_reference_test.cc",
"ble_connection_info_test.cc",
"ble_test.cc",
"ble_v2_test.cc",
"bluetooth_adapter_test.cc",
"bluetooth_classic_test.cc",
"bluetooth_connection_info_test.cc",
"borrowable_test.cc",
"cancelable_alarm_test.cc",
"condition_variable_test.cc",
"connection_info_test.cc",
"count_down_latch_test.cc",
"credential_storage_impl_test.cc",
"crypto_test.cc",
"direct_executor_test.cc",
"future_test.cc",
"logging_test.cc",
"multi_thread_executor_test.cc",
"mutex_test.cc",
"pipe_test.cc",
"scheduled_executor_test.cc",
"single_thread_executor_test.cc",
"task_runner_impl_test.cc",
"timer_impl_test.cc",
"uuid_test.cc",
"wifi_direct_test.cc",
"wifi_hotspot_test.cc",
"wifi_lan_connection_info_test.cc",
"wifi_lan_test.cc",
"wifi_test.cc",
"wifi_utils_test.cc",
],
copts = ["-DCORE_ADAPTER_DLL"],
shard_count = 16,
deps = [
":base",
@@ -470,16 +521,29 @@ cc_test(
":test_util",
":types",
":uuid",
"//internal/crypto_cros",
"//internal/flags:nearby_flags",
"//internal/platform/flags:platform_flags",
"//internal/platform/implementation:comm",
"//internal/platform/implementation/g3", # build_cleaner: keep
"//internal/proto:credential_cc_proto",
"//internal/test",
"//proto:connections_enums_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/log",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/synchronization",
"@com_google_absl//absl/time",
"@com_google_absl//absl/types:variant",
"@com_google_googletest//:gtest_main",
],
] + select({
"@platforms//os:windows": [
"//internal/platform/implementation/windows",
],
"//conditions:default": [
"//internal/platform/implementation/g3",
],
}),
)
+104
View File
@@ -0,0 +1,104 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PLATFORM_PUBLIC_ARRAY_BLOCKING_QUEUE_H_
#define PLATFORM_PUBLIC_ARRAY_BLOCKING_QUEUE_H_
#include <cstddef>
#include <optional>
#include <queue>
#include "internal/platform/condition_variable.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex.h"
#include "internal/platform/mutex_lock.h"
namespace nearby {
/**
* Payload from different services/clients will be put into an
* ArrayBlockingQueue before sending to ensure each client has equal chance to
* send its data. Since C++ doesn't provide ArrayBlockingQueue as Java, we
* implement one here.
*/
template <typename T>
class ArrayBlockingQueue {
public:
explicit ArrayBlockingQueue(size_t capacity) : capacity_(capacity) {}
void Put(const T& value) {
MutexLock lock(&queue_mutex_);
if (queue_.size() >= capacity_) {
has_space_.Wait();
}
queue_.push(value);
NEARBY_LOGS(INFO) << "ArrayBlockingQueue::Put()";
has_data_.Notify();
}
T Take() {
MutexLock lock(&queue_mutex_);
if (queue_.empty()) {
has_data_.Wait();
}
T front = queue_.front();
queue_.pop();
NEARBY_LOGS(INFO) << "ArrayBlockingQueue::Take()";
has_space_.Notify();
return front;
}
bool TryPut(const T& value) {
MutexLock lock(&queue_mutex_);
if (queue_.size() < capacity_) {
queue_.push(value);
has_data_.Notify();
return true;
}
return false;
}
// Returns std::nullopt if the queue is empty.
std::optional<T> TryTake() {
MutexLock lock(&queue_mutex_);
if (!queue_.empty()) {
T front = queue_.front();
queue_.pop();
has_space_.Notify();
return front;
}
return std::nullopt;
}
size_t Size() const {
MutexLock lock(&queue_mutex_);
return queue_.size();
}
bool Empty() const {
MutexLock lock(&queue_mutex_);
return queue_.empty();
}
private:
std::queue<T> queue_;
mutable Mutex queue_mutex_;
ConditionVariable has_data_{&queue_mutex_};
ConditionVariable has_space_{&queue_mutex_};
const size_t capacity_;
};
} // namespace nearby
#endif // PLATFORM_PUBLIC_ARRAY_BLOCKING_QUEUE_H_
+1 -2
View File
@@ -27,9 +27,8 @@ namespace nearby {
// cpp/platform/api/atomic_boolean.h
class AtomicBoolean final : public api::AtomicBoolean {
public:
using Platform = api::ImplementationPlatform;
explicit AtomicBoolean(bool value = false)
: impl_(Platform::CreateAtomicBoolean(value)) {}
: impl_(api::ImplementationPlatform::CreateAtomicBoolean(value)) {}
~AtomicBoolean() override = default;
AtomicBoolean(AtomicBoolean&&) = default;
AtomicBoolean& operator=(AtomicBoolean&&) = default;
-2
View File
@@ -14,8 +14,6 @@
#include "internal/platform/atomic_boolean.h"
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
namespace nearby {
+43
View File
@@ -14,8 +14,16 @@
#include "internal/platform/base64_utils.h"
#include <cstdint>
#include <string>
#include <utility>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
namespace nearby {
@@ -36,4 +44,39 @@ ByteArray Base64Utils::Decode(absl::string_view base64_string) {
return ByteArray(decoded_string.data(), decoded_string.size());
}
std::int32_t Base64Utils::BytesToInt(const ByteArray& bytes) {
const char* int_bytes = bytes.data();
std::int32_t result = 0;
result |= (static_cast<std::int32_t>(int_bytes[0]) & 0x0FF) << 24;
result |= (static_cast<std::int32_t>(int_bytes[1]) & 0x0FF) << 16;
result |= (static_cast<std::int32_t>(int_bytes[2]) & 0x0FF) << 8;
result |= (static_cast<std::int32_t>(int_bytes[3]) & 0x0FF);
return result;
}
ByteArray Base64Utils::IntToBytes(std::int32_t value) {
char int_bytes[sizeof(std::int32_t)];
int_bytes[0] = static_cast<char>((value >> 24) & 0x0FF);
int_bytes[1] = static_cast<char>((value >> 16) & 0x0FF);
int_bytes[2] = static_cast<char>((value >> 8) & 0x0FF);
int_bytes[3] = static_cast<char>((value) & 0x0FF);
return ByteArray(int_bytes, sizeof(int_bytes));
}
ExceptionOr<std::int32_t> Base64Utils::ReadInt(InputStream* reader) {
ExceptionOr<ByteArray> read_bytes = reader->ReadExactly(sizeof(std::int32_t));
if (!read_bytes.ok()) {
return ExceptionOr<std::int32_t>(read_bytes.exception());
}
return ExceptionOr<std::int32_t>(
BytesToInt(std::move(read_bytes.result())));
}
Exception Base64Utils::WriteInt(OutputStream* writer, std::int32_t value) {
return writer->Write(IntToBytes(value));
}
} // namespace nearby
+9
View File
@@ -15,8 +15,13 @@
#ifndef PLATFORM_BASE_BASE64_UTILS_H_
#define PLATFORM_BASE_BASE64_UTILS_H_
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/output_stream.h"
namespace nearby {
@@ -24,6 +29,10 @@ class Base64Utils {
public:
static std::string Encode(const ByteArray& bytes);
static ByteArray Decode(absl::string_view base64_string);
static std::int32_t BytesToInt(const ByteArray& bytes);
static ByteArray IntToBytes(std::int32_t value);
static ExceptionOr<std::int32_t> ReadInt(InputStream* reader);
static Exception WriteInt(OutputStream* writer, std::int32_t value);
};
} // namespace nearby
+4
View File
@@ -15,6 +15,10 @@
#ifndef PLATFORM_BASE_BASE_INPUT_STREAM_H_
#define PLATFORM_BASE_BASE_INPUT_STREAM_H_
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/input_stream.h"
-38
View File
@@ -1,38 +0,0 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PLATFORM_BASE_BASE_MUTEX_LOCK_H_
#define PLATFORM_BASE_BASE_MUTEX_LOCK_H_
#include "absl/base/thread_annotations.h"
#include "internal/platform/implementation/mutex.h"
namespace nearby {
// An RAII mechanism to acquire a Lock over a block of code.
class ABSL_SCOPED_LOCKABLE BaseMutexLock final {
public:
explicit BaseMutexLock(api::Mutex* mutex) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex)
: mutex_(mutex) {
mutex_->Lock();
}
~BaseMutexLock() ABSL_UNLOCK_FUNCTION() { mutex_->Unlock(); }
private:
api::Mutex* mutex_;
};
} // namespace nearby
#endif // PLATFORM_BASE_BASE_MUTEX_LOCK_H_
+25 -17
View File
@@ -14,6 +14,13 @@
#include "internal/platform/ble.h"
#include <memory>
#include <string>
#include <utility>
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/ble.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h"
@@ -49,13 +56,11 @@ bool BleMedium::StartScanning(
auto pair = peripherals_.emplace(
&peripheral, absl::make_unique<ScanningInfo>());
auto& context = *pair.first->second;
if (pair.second) {
context.peripheral = BlePeripheral(&peripheral);
discovered_peripheral_callback_.peripheral_discovered_cb(
context.peripheral, service_id,
context.peripheral.GetAdvertisementBytes(service_id),
fast_advertisement);
}
context.peripheral = BlePeripheral(&peripheral);
discovered_peripheral_callback_.peripheral_discovered_cb(
context.peripheral, service_id,
context.peripheral.GetAdvertisementBytes(service_id),
fast_advertisement);
},
.peripheral_lost_cb =
[this](api::BlePeripheral& peripheral,
@@ -64,8 +69,9 @@ bool BleMedium::StartScanning(
if (peripherals_.empty()) return;
auto context = peripherals_.find(&peripheral);
if (context == peripherals_.end()) return;
NEARBY_LOG(INFO, "Removing peripheral=%p, impl=%p",
&(context->second->peripheral), &peripheral);
NEARBY_LOGS(INFO) << "Removing peripheral="
<< context->second->peripheral.GetName()
<< ", impl=" << &peripheral;
discovered_peripheral_callback_.peripheral_lost_cb(
context->second->peripheral, service_id);
},
@@ -77,7 +83,7 @@ bool BleMedium::StopScanning(const std::string& service_id) {
MutexLock lock(&mutex_);
discovered_peripheral_callback_ = {};
peripherals_.clear();
NEARBY_LOG(INFO, "Ble Scanning disabled: impl=%p", &GetImpl());
NEARBY_LOGS(INFO) << "Ble Scanning disabled: impl=" << &GetImpl();
}
return impl_->StopScanning(service_id);
}
@@ -96,12 +102,12 @@ bool BleMedium::StartAcceptingConnections(const std::string& service_id,
&socket, std::make_unique<AcceptedConnectionInfo>());
auto& context = *pair.first->second;
if (!pair.second) {
NEARBY_LOG(INFO, "Accepting (again) socket=%p, impl=%p",
&context.socket, &socket);
NEARBY_LOGS(INFO) << "Accepting (again) socket=" << &context.socket
<< ", impl=" << &socket;
} else {
context.socket = BleSocket(&socket);
NEARBY_LOG(INFO, "Accepting socket=%p, impl=%p", &context.socket,
&socket);
NEARBY_LOGS(INFO)
<< "Accepting socket=" << &context.socket << ", impl=" << &socket;
}
if (accepted_connection_callback_) {
accepted_connection_callback_(context.socket, service_id);
@@ -114,7 +120,8 @@ bool BleMedium::StopAcceptingConnections(const std::string& service_id) {
MutexLock lock(&mutex_);
accepted_connection_callback_ = nullptr;
sockets_.clear();
NEARBY_LOG(INFO, "Ble accepted connection disabled: impl=%p", &GetImpl());
NEARBY_LOGS(INFO) << "Ble accepted connection disabled: impl="
<< &GetImpl();
}
return impl_->StopAcceptingConnections(service_id);
}
@@ -124,8 +131,9 @@ BleSocket BleMedium::Connect(BlePeripheral& peripheral,
CancellationFlag* cancellation_flag) {
{
MutexLock lock(&mutex_);
NEARBY_LOG(INFO, "BleMedium::Connect: peripheral=%p [impl=%p]", &peripheral,
&peripheral.GetImpl());
NEARBY_LOGS(INFO) << "BleMedium::Connect: peripheral="
<< peripheral.GetName()
<< ",impl=" << &peripheral.GetImpl();
}
return BleSocket(
impl_->Connect(peripheral.GetImpl(), service_id, cancellation_flag));
+16 -14
View File
@@ -15,10 +15,14 @@
#include "internal/platform/ble.h"
#include <memory>
#include <string>
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/count_down_latch.h"
#include "internal/platform/logging.h"
#include "internal/platform/medium_environment.h"
@@ -74,11 +78,10 @@ TEST_P(BleMediumTest, CanStartAcceptingConnectionsAndConnect) {
BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes,
bool fast_advertisement) {
NEARBY_LOG(
INFO,
"Peripheral discovered: %s, %p, fast advertisement: %d",
peripheral.GetName().c_str(), &peripheral,
fast_advertisement);
NEARBY_LOGS(INFO)
<< "Discovered peripheral=" << peripheral.GetName()
<< ", impl=" << &peripheral.GetImpl()
<< ", fast advertisement=" << fast_advertisement;
discovered_peripheral = &peripheral;
found_latch.CountDown();
},
@@ -87,8 +90,8 @@ TEST_P(BleMediumTest, CanStartAcceptingConnectionsAndConnect) {
fast_advertisement_service_uuid);
ble_b.StartAcceptingConnections(
service_id, [&](BleSocket socket, const std::string& service_id) {
NEARBY_LOG(INFO, "Connection accepted: socket=%p, service_id=%s",
&socket, service_id.c_str());
NEARBY_LOGS(INFO) << "Connection accepted: socket=" << &socket
<< ", service_id=" << service_id;
accepted_latch.CountDown();
});
EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
@@ -133,11 +136,10 @@ TEST_P(BleMediumTest, CanCancelConnect) {
BlePeripheral& peripheral, const std::string& service_id,
const ByteArray& advertisement_bytes,
bool fast_advertisement) {
NEARBY_LOG(
INFO,
"Peripheral discovered: %s, %p, fast advertisement: %d",
peripheral.GetName().c_str(), &peripheral,
fast_advertisement);
NEARBY_LOGS(INFO)
<< "Discovered peripheral=" << peripheral.GetName()
<< ", impl=" << &peripheral.GetImpl()
<< ", fast advertisement=" << fast_advertisement;
discovered_peripheral = &peripheral;
found_latch.CountDown();
},
@@ -146,8 +148,8 @@ TEST_P(BleMediumTest, CanCancelConnect) {
fast_advertisement_service_uuid);
ble_b.StartAcceptingConnections(
service_id, [&](BleSocket socket, const std::string& service_id) {
NEARBY_LOG(INFO, "Connection accepted: socket=%p, service_id=%s",
&socket, service_id.c_str());
NEARBY_LOGS(INFO) << "Connection accepted: socket=" << &socket
<< ", service_id=" << service_id;
accepted_latch.CountDown();
});
EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
+6 -60
View File
@@ -22,6 +22,7 @@
#include "internal/platform/implementation/ble_v2.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h"
#include "internal/platform/uuid.h"
namespace nearby {
@@ -43,26 +44,6 @@ bool BleV2Medium::StartAdvertising(
bool BleV2Medium::StopAdvertising() { return impl_->StopAdvertising(); }
std::unique_ptr<api::ble_v2::BleMedium::AdvertisingSession>
BleV2Medium::StartAdvertisingTmp(
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters,
api::ble_v2::BleMedium::AdvertisingCallback callback) {
if (impl_->StartAdvertising(advertising_data, advertise_set_parameters)) {
callback.start_advertising_result(absl::OkStatus());
} else {
callback.start_advertising_result(
absl::InternalError("Failed to start advertising"));
return nullptr;
}
return std::make_unique<api::ble_v2::BleMedium::AdvertisingSession>(
api::ble_v2::BleMedium::AdvertisingSession{.stop_advertising = [this] {
return impl_->StopAdvertising()
? absl::OkStatus()
: absl::InternalError("Failed to stop advertising");
}});
}
std::unique_ptr<api::ble_v2::BleMedium::AdvertisingSession>
BleV2Medium::StartAdvertising(
const api::ble_v2::BleAdvertisementData& advertising_data,
@@ -111,7 +92,7 @@ bool BleV2Medium::StartScanning(const Uuid& service_uuid,
// prevent the stale data in cache.
peripherals_.clear();
scanning_enabled_ = true;
NEARBY_LOG(INFO, "Ble Scanning enabled; impl=%p", GetImpl());
NEARBY_LOGS(INFO) << "Ble Scanning enabled; impl=" << GetImpl();
}
return success;
}
@@ -126,51 +107,15 @@ bool BleV2Medium::StopScanning() {
scanning_enabled_ = false;
peripherals_.clear();
scan_callback_ = {};
NEARBY_LOG(INFO, "Ble Scanning disabled: impl=%p", GetImpl());
NEARBY_LOGS(INFO) << "Ble Scanning disabled: impl=" << GetImpl();
return impl_->StopScanning();
}
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession>
BleV2Medium::StartScanningTmp(
const Uuid& service_uuid, api::ble_v2::TxPowerLevel tx_power_level,
api::ble_v2::BleMedium::ScanningCallback callback) {
MutexLock lock(&mutex_);
if (impl_->StartScanning(
service_uuid, tx_power_level,
api::ble_v2::BleMedium::ScanCallback{
.advertisement_found_cb =
[this,
found_callback = std::move(callback.advertisement_found_cb)](
api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) mutable {
MutexLock lock(&mutex_);
if (!peripherals_.contains(&peripheral)) {
NEARBY_LOGS(INFO)
<< "Peripheral impl=" << &peripheral
<< " does not exist; add it to the map.";
peripherals_.insert(&peripheral);
}
found_callback(peripheral, advertisement_data);
},
})) {
callback.start_scanning_result(absl::OkStatus());
} else {
callback.start_scanning_result(absl::InternalError("Failed to start scan"));
return nullptr;
}
return std::make_unique<api::ble_v2::BleMedium::ScanningSession>(
api::ble_v2::BleMedium::ScanningSession{.stop_scanning = [this]() {
return impl_->StopScanning()
? absl::OkStatus()
: absl::InternalError("Failed to stop advertising");
}});
}
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession>
BleV2Medium::StartScanning(const Uuid& service_uuid,
api::ble_v2::TxPowerLevel tx_power_level,
api::ble_v2::BleMedium::ScanningCallback callback) {
NEARBY_LOG(INFO, "platform mutex: %p", &mutex_);
NEARBY_LOGS(INFO) << "platform mutex: " << &mutex_;
return impl_->StartScanning(
service_uuid, tx_power_level,
api::ble_v2::BleMedium::ScanningCallback{
@@ -187,6 +132,7 @@ BleV2Medium::StartScanning(const Uuid& service_uuid,
start_scanning_result(status);
},
.advertisement_found_cb = std::move(callback.advertisement_found_cb),
.advertisement_lost_cb = std::move(callback.advertisement_lost_cb),
});
}
@@ -280,7 +226,7 @@ BleV2Socket BleV2Medium::Connect(const std::string& service_id,
}
bool BleV2Medium::IsExtendedAdvertisementsAvailable() {
return impl_->IsExtendedAdvertisementsAvailable();
return IsValid() && impl_->IsExtendedAdvertisementsAvailable();
}
BleV2Peripheral BleV2Medium::GetRemotePeripheral(
+1 -18
View File
@@ -375,7 +375,7 @@ class BleV2Medium final {
// Returns true once the BLE advertising has been initiated.
// This interface will be deprecated soon.
// TODO(b/271305977) remove this function.
// Use 'unique_ptr<AdvertisingSession> StartAdvertisingTmp' instead.
// Use 'unique_ptr<AdvertisingSession> StartAdvertising' instead.
bool StartAdvertising(
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_parameters);
@@ -383,14 +383,6 @@ class BleV2Medium final {
// TODO(b/271305977) remove this function.
bool StopAdvertising();
// Temp interface for windows client to use before windows has native impl
// for 'unique_ptr<AdvertisingSession> StartAdvertising'.
// TODO(b/271305977) remove this function.
std::unique_ptr<api::ble_v2::BleMedium::AdvertisingSession>
StartAdvertisingTmp(const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters,
api::ble_v2::BleMedium::AdvertisingCallback callback);
std::unique_ptr<api::ble_v2::BleMedium::AdvertisingSession> StartAdvertising(
const api::ble_v2::BleAdvertisementData& advertising_data,
api::ble_v2::AdvertiseParameters advertise_set_parameters,
@@ -398,8 +390,6 @@ class BleV2Medium final {
// Returns true once the BLE scan has been initiated.
// This interface will be deprecated soon.
// TODO(b/271305977) remove this function.
// Use 'unique_ptr<ScanningSession> StartScanningTmp' instead.
bool StartScanning(const Uuid& service_uuid,
api::ble_v2::TxPowerLevel tx_power_level,
ScanCallback callback);
@@ -411,13 +401,6 @@ class BleV2Medium final {
const Uuid& service_uuid, api::ble_v2::TxPowerLevel tx_power_level,
api::ble_v2::BleMedium::ScanningCallback callback);
// Temp interface for windows client to use before windows has native impl
// for 'unique_ptr<AdvertisingSession> StartScanning'.
// TODO(b/271305977) remove this function.
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession> StartScanningTmp(
const Uuid& service_uuid, api::ble_v2::TxPowerLevel tx_power_level,
api::ble_v2::BleMedium::ScanningCallback callback);
// Starts Gatt Server for waiting to client connection.
std::unique_ptr<GattServer> StartGattServer(
ServerGattConnectionCallback callback);
-50
View File
@@ -434,56 +434,6 @@ TEST_F(BleV2MediumTest, CanStartAsyncScanningAndAdvertising) {
env_.Stop();
}
TEST_F(BleV2MediumTest, CanStartAsyncScanningAndAdvertisingWithTmpImpl) {
env_.Start();
BluetoothAdapter adapter_a;
BluetoothAdapter adapter_b;
BleV2Medium ble_a(adapter_a);
BleV2Medium ble_b(adapter_b);
Uuid service_uuid(1234, 5678);
ByteArray advertisement_bytes{std::string(kAdvertisementString)};
ByteArray advertisement_header_bytes{std::string(kAdvertisementHeaderString)};
CountDownLatch found_latch(1);
std::unique_ptr<api::ble_v2::BleMedium::ScanningSession> scanning_session =
ble_a.StartScanningTmp(
service_uuid, kTxPowerLevel,
api::ble_v2::BleMedium::ScanningCallback{
.advertisement_found_cb =
[&](api::ble_v2::BlePeripheral& peripheral,
BleAdvertisementData advertisement_data) -> void {
found_latch.CountDown();
},
});
// Succeed to start regular advertisement.
BleAdvertisementData advertising_data;
advertising_data.is_extended_advertisement = false;
advertising_data.service_data = {{service_uuid, advertisement_header_bytes}};
std::unique_ptr<api::ble_v2::BleMedium::AdvertisingSession> adv_session =
ble_b.StartAdvertisingTmp(
advertising_data,
{.tx_power_level = kTxPowerLevel, .is_connectable = true},
{.start_advertising_result = [](absl::Status) {}});
EXPECT_NE(adv_session, nullptr);
EXPECT_TRUE(env_.GetBleV2MediumStatus(*ble_a.GetImpl()).value().is_scanning);
EXPECT_TRUE(
env_.GetBleV2MediumStatus(*ble_b.GetImpl()).value().is_advertising);
EXPECT_TRUE(found_latch.Await(kWaitDuration).result());
EXPECT_OK(scanning_session->stop_scanning());
EXPECT_OK(adv_session->stop_advertising());
EXPECT_FALSE(env_.GetBleV2MediumStatus(*ble_a.GetImpl()).value().is_scanning);
EXPECT_FALSE(
env_.GetBleV2MediumStatus(*ble_b.GetImpl()).value().is_advertising);
env_.UnregisterBleV2Medium(*ble_a.GetImpl());
env_.UnregisterBleV2Medium(*ble_b.GetImpl());
EXPECT_EQ(env_.GetBleV2MediumStatus(*ble_a.GetImpl()), absl::nullopt);
EXPECT_EQ(env_.GetBleV2MediumStatus(*ble_b.GetImpl()), absl::nullopt);
env_.Stop();
}
TEST_F(BleV2MediumTest, CanStartGattServer) {
env_.Start();
BluetoothAdapter adapter;
@@ -0,0 +1,72 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/platform/blocking_queue_stream.h"
#include <cstdint>
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/logging.h"
namespace nearby {
BlockingQueueStream::BlockingQueueStream() {
NEARBY_LOGS(INFO) << "Create a BlockingQueueStream with size "
<< FeatureFlags::GetInstance()
.GetFlags()
.blocking_queue_stream_queue_capacity;
}
ExceptionOr<ByteArray> BlockingQueueStream::Read(std::int64_t size) {
if (is_closed_) {
NEARBY_LOGS(INFO)
<< "Failed to read BlockingQueueStream because it was closed.";
return ExceptionOr<ByteArray>(Exception::kInterrupted);
}
NEARBY_LOGS(INFO) << "BlockingQueueStream expect to read " << size
<< " bytes";
return ExceptionOr<ByteArray>(blocking_queue_.Take());
}
void BlockingQueueStream::Write(const ByteArray& bytes) {
if (is_closed_) {
NEARBY_LOGS(INFO)
<< "Failed to write BlockingQueueStream because it was closed.";
return;
}
is_writing_ = true;
blocking_queue_.Put(bytes);
is_writing_ = false;
NEARBY_VLOG(1) << "BlockingQueueStream wrote " << bytes.size() << " bytes";
}
Exception BlockingQueueStream::Close() {
if (is_closed_) {
NEARBY_LOGS(INFO) << "InputBlockingQueueStream has already been closed.";
return {Exception::kSuccess};
}
if (is_writing_) {
NEARBY_LOGS(INFO)
<< "BlockingQueueStream is waiting for writing, read first to unblock";
blocking_queue_.TryTake();
}
blocking_queue_.TryPut(queue_end_);
is_closed_ = true;
NEARBY_LOGS(INFO) << "InputBlockingQueueStream is closed.";
return {Exception::kSuccess};
}
} // namespace nearby
+52
View File
@@ -0,0 +1,52 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PLATFORM_PUBLIC_BLOCKING_QUEUE_STREAM_H_
#define PLATFORM_PUBLIC_BLOCKING_QUEUE_STREAM_H_
#include <cstdint>
#include "internal/platform/array_blocking_queue.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/exception.h"
#include "internal/platform/feature_flags.h"
#include "internal/platform/input_stream.h"
#include "internal/platform/mutex.h"
namespace nearby {
class BlockingQueueStream : public InputStream {
public:
BlockingQueueStream();
~BlockingQueueStream() override = default;
ExceptionOr<ByteArray> Read(std::int64_t size) override;
void Write(const ByteArray& bytes);
Exception Close() override;
bool IsWriting() const {
return is_writing_;
}
private:
mutable Mutex mutex_;
ArrayBlockingQueue<ByteArray> blocking_queue_{FeatureFlags::GetInstance()
.GetFlags()
.blocking_queue_stream_queue_capacity};
ByteArray queue_end_{0};
bool is_writing_ = false;
bool is_closed_ = false;
};
} // namespace nearby
#endif // #ifndef PLATFORM_PUBLIC_BLOCKING_QUEUE_STREAM_H_
+92 -17
View File
@@ -14,76 +14,132 @@
#include "internal/platform/bluetooth_classic.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/cancellation_flag.h"
#include "internal/platform/implementation/bluetooth_classic.h"
#include "internal/platform/logging.h"
#include "internal/platform/mutex_lock.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/socket.h"
namespace nearby {
using location::nearby::proto::connections::Medium;
MediumSocket* BluetoothSocket::CreateVirtualSocket(OutputStream* outputstream) {
if (IsVirtualSocket()) {
LOG(WARNING)
<< "Creating the virtual socket on a virtual socket is not allowed.";
return nullptr;
}
auto virtual_socket = std::make_shared<BluetoothSocket>(outputstream);
return virtual_socket.get();
}
MediumSocket* BluetoothSocket::CreateVirtualSocket(
const std::string& salted_service_id_hash_key, OutputStream* outputstream,
Medium medium,
absl::flat_hash_map<std::string, std::shared_ptr<MediumSocket>>*
virtual_sockets_ptr) {
if (IsVirtualSocket()) {
LOG(WARNING)
<< "Creating the virtual socket on a virtual socket is not allowed.";
return nullptr;
}
auto virtual_socket = std::make_shared<BluetoothSocket>(outputstream);
virtual_socket->impl_ = this->impl_;
LOG(WARNING) << "Created the virtual socket for Medium: "
<< Medium_Name(virtual_socket->GetMedium());
if (virtual_sockets_ptr_ == nullptr) {
virtual_sockets_ptr_ = virtual_sockets_ptr;
}
(*virtual_sockets_ptr_)[salted_service_id_hash_key] = virtual_socket;
LOG(INFO) << "virtual_sockets_ size: " << virtual_sockets_ptr_->size();
return virtual_socket.get();
}
BluetoothClassicMedium::~BluetoothClassicMedium() {
LOG(INFO) << "~BluetoothClassicMedium: observer_list_ size: "
<< observer_list_.size();
if (!observer_list_.empty()) {
impl_->RemoveObserver(this);
}
StopDiscovery();
LOG(INFO) << "eof ~BluetoothClassicMedium";
}
BluetoothSocket BluetoothClassicMedium::ConnectToService(
BluetoothDevice& remote_device, const std::string& service_uuid,
CancellationFlag* cancellation_flag) {
NEARBY_LOG(INFO,
"BluetoothClassicMedium::ConnectToService: device=%p [impl=%p]",
&remote_device, &remote_device.GetImpl());
LOG(INFO) << "BluetoothClassicMedium::ConnectToService: "
"service_uuid="
<< service_uuid << ", device=" << remote_device.GetMacAddress()
<< ", [impl=" << &remote_device.GetImpl() << "]";
return BluetoothSocket(impl_->ConnectToService(
remote_device.GetImpl(), service_uuid, cancellation_flag));
}
bool BluetoothClassicMedium::StartDiscovery(DiscoveryCallback callback) {
LOG(INFO) << "BluetoothClassicMedium::StartDiscovery";
MutexLock lock(&mutex_);
if (discovery_enabled_) {
NEARBY_LOG(INFO, "BT Discovery already enabled; impl=%p", &GetImpl());
LOG(INFO) << "BT Discovery already enabled; impl=" << &GetImpl();
return false;
}
bool success = impl_->StartDiscovery({
.device_discovered_cb =
[this](api::BluetoothDevice& device) {
VLOG(1) << "BT .device_discovered_cb for " << device.GetName();
MutexLock lock(&mutex_);
auto pair = devices_.emplace(
&device, absl::make_unique<DeviceDiscoveryInfo>());
&device, std::make_unique<DeviceDiscoveryInfo>());
auto& context = *pair.first->second;
if (!pair.second) {
NEARBY_LOG(INFO, "Adding (again) device=%p, impl=%p",
&context.device, &device);
LOG(INFO) << "Adding (again) device="
<< context.device.GetMacAddress()
<< ",impl=" << &device;
return;
}
context.device = BluetoothDevice(&device);
NEARBY_LOG(INFO, "Adding device=%p, impl=%p", &context.device,
&device);
LOG(INFO) << "Adding device=" << context.device.GetMacAddress()
<< ",impl=" << &device;
if (!discovery_enabled_) return;
discovery_callback_.device_discovered_cb(context.device);
},
.device_name_changed_cb =
[this](api::BluetoothDevice& device) {
VLOG(1) << "BT .device_name_changed_cb for " << device.GetName();
MutexLock lock(&mutex_);
// If the device is not already in devices_, we should not be able
// to change its name.
if (devices_.find(&device) == devices_.end()) return;
auto& context = *devices_[&device];
NEARBY_LOG(INFO, "Renaming device=%p, impl=%p", &context.device,
&device);
LOG(INFO) << "Renaming device=" << context.device.GetMacAddress()
<< ",impl=" << &device;
if (!discovery_enabled_) return;
discovery_callback_.device_name_changed_cb(context.device);
},
.device_lost_cb =
[this](api::BluetoothDevice& device) {
VLOG(1) << "BT .device_lost_cb for " << device.GetMacAddress();
MutexLock lock(&mutex_);
auto item = devices_.extract(&device);
if (!item) {
NEARBY_LOGS(WARNING)
<< "Removing unknown device: " << device.GetMacAddress();
LOG(WARNING) << "Removing unknown device: "
<< device.GetMacAddress();
return;
}
auto& context = *item.mapped();
NEARBY_LOG(INFO, "Removing device=%p, impl=%p", &context.device,
&device);
LOG(INFO) << "Removing device=" << context.device.GetMacAddress()
<< ",impl=" << &device;
if (!discovery_enabled_) return;
discovery_callback_.device_lost_cb(context.device);
},
@@ -92,44 +148,54 @@ bool BluetoothClassicMedium::StartDiscovery(DiscoveryCallback callback) {
discovery_callback_ = std::move(callback);
devices_.clear();
discovery_enabled_ = true;
NEARBY_LOG(INFO, "BT Discovery enabled; impl=%p", &GetImpl());
}
LOG(INFO) << "BT StartDiscovery result:" << success
<< ", impl=" << &GetImpl();
return success;
}
bool BluetoothClassicMedium::StopDiscovery() {
LOG(INFO) << "BT StopDiscovery; impl=" << &GetImpl();
MutexLock lock(&mutex_);
if (!discovery_enabled_) return true;
discovery_enabled_ = false;
discovery_callback_ = {};
devices_.clear();
NEARBY_LOG(INFO, "BT Discovery disabled: impl=%p", &GetImpl());
LOG(INFO) << "BT Discovery disabled: impl=" << &GetImpl();
return impl_->StopDiscovery();
}
void BluetoothClassicMedium::AddObserver(Observer* observer) {
LOG(INFO) << "BT AddObserver; impl=" << &GetImpl();
MutexLock lock(&mutex_);
if (observer_list_.empty()) {
impl_->AddObserver(this);
}
observer_list_.AddObserver(observer);
LOG(INFO) << "BT AddObserver done";
}
void BluetoothClassicMedium::RemoveObserver(Observer* observer) {
LOG(INFO) << "BT RemoveObserver; impl=" << &GetImpl();
MutexLock lock(&mutex_);
observer_list_.RemoveObserver(observer);
if (observer_list_.empty()) {
impl_->RemoveObserver(this);
}
LOG(INFO) << "BT RemoveObserver done";
}
// api::BluetoothClassicMedium::Observer methods
void BluetoothClassicMedium::DeviceAdded(api::BluetoothDevice& device) {
VLOG(1) << "BT DeviceAdded; name=" << device.GetName()
<< ", address=" << device.GetMacAddress();
BluetoothDevice bt_device(&device);
for (auto* observer : observer_list_.GetObservers()) {
observer->DeviceAdded(bt_device);
}
}
void BluetoothClassicMedium::DeviceRemoved(api::BluetoothDevice& device) {
VLOG(1) << "BT DeviceRemoved; name=" << device.GetName()
<< ", address=" << device.GetMacAddress();
BluetoothDevice bt_device(&device);
for (auto* observer : observer_list_.GetObservers()) {
observer->DeviceRemoved(bt_device);
@@ -137,6 +203,9 @@ void BluetoothClassicMedium::DeviceRemoved(api::BluetoothDevice& device) {
}
void BluetoothClassicMedium::DeviceAddressChanged(
api::BluetoothDevice& device, absl::string_view old_address) {
VLOG(1) << "BT DeviceAddressChanged; name=" << device.GetName()
<< ", address=" << device.GetMacAddress()
<< ", old_address=" << old_address;
BluetoothDevice bt_device(&device);
for (auto* observer : observer_list_.GetObservers()) {
observer->DeviceAddressChanged(bt_device, old_address);
@@ -144,6 +213,9 @@ void BluetoothClassicMedium::DeviceAddressChanged(
}
void BluetoothClassicMedium::DevicePairedChanged(api::BluetoothDevice& device,
bool new_paired_status) {
VLOG(1) << "BT DevicePairedChanged; name=" << device.GetName()
<< ", address=" << device.GetMacAddress()
<< ", status=" << new_paired_status;
BluetoothDevice bt_device(&device);
for (auto* observer : observer_list_.GetObservers()) {
observer->DevicePairedChanged(bt_device, new_paired_status);
@@ -151,6 +223,9 @@ void BluetoothClassicMedium::DevicePairedChanged(api::BluetoothDevice& device,
}
void BluetoothClassicMedium::DeviceConnectedStateChanged(
api::BluetoothDevice& device, bool connected) {
VLOG(1) << "BT DeviceConnectedStateChanged: name=" << device.GetName()
<< ", address=" << device.GetMacAddress()
<< ", connected=" << connected;
BluetoothDevice bt_device(&device);
for (auto* observer : observer_list_.GetObservers()) {
observer->DeviceConnectedStateChanged(bt_device, connected);
+72 -9
View File
@@ -15,14 +15,19 @@
#ifndef PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
#define PLATFORM_PUBLIC_BLUETOOTH_CLASSIC_H_
#include <stdbool.h>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/functional/any_invocable.h"
#include "absl/strings/string_view.h"
#include "internal/base/observer_list.h"
#include "internal/platform/blocking_queue_stream.h"
#include "internal/platform/bluetooth_adapter.h"
#include "internal/platform/byte_array.h"
#include "internal/platform/cancellation_flag.h"
@@ -34,29 +39,79 @@
#include "internal/platform/logging.h"
#include "internal/platform/mutex.h"
#include "internal/platform/output_stream.h"
#include "internal/platform/socket.h"
namespace nearby {
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
class BluetoothSocket final {
class BluetoothSocket : public MediumSocket {
public:
BluetoothSocket() = default;
BluetoothSocket()
: MediumSocket(location::nearby::proto::connections::Medium::BLUETOOTH) {
};
BluetoothSocket(const BluetoothSocket&) = default;
BluetoothSocket& operator=(const BluetoothSocket&) = default;
// Creates a physical BluetoothSocket from a platform implementation.
explicit BluetoothSocket(std::unique_ptr<api::BluetoothSocket> socket)
: impl_(socket.release()) {}
~BluetoothSocket() = default;
: MediumSocket(location::nearby::proto::connections::Medium::BLUETOOTH),
impl_(socket.release()) {}
// Creates a virtual BluetoothSocket from a virtual output stream.
explicit BluetoothSocket(OutputStream* virtual_output_stream)
: MediumSocket(location::nearby::proto::connections::Medium::BLUETOOTH),
blocking_queue_input_stream_(std::make_shared<BlockingQueueStream>()),
virtual_output_stream_(virtual_output_stream),
is_virtual_socket_(true) {}
~BluetoothSocket() override = default;
// Returns the InputStream of this connected BluetoothSocket.
InputStream& GetInputStream() { return impl_->GetInputStream(); }
InputStream& GetInputStream() override {
return IsVirtualSocket() ? *blocking_queue_input_stream_
: impl_->GetInputStream();
}
// Returns the OutputStream of this connected BluetoothSocket.
OutputStream& GetOutputStream() { return impl_->GetOutputStream(); }
OutputStream& GetOutputStream() override {
return IsVirtualSocket() ? *virtual_output_stream_
: impl_->GetOutputStream();
}
// Closes both input and output streams, marks Socket as closed.
// After this call object should be treated as not connected.
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
Exception Close() { return impl_->Close(); }
Exception Close() override {
if (IsVirtualSocket()) {
NEARBY_LOGS(INFO) << "Multiplex: Closing virtual socket: " << this;
blocking_queue_input_stream_->Close();
virtual_output_stream_->Close();
CloseLocal();
return {Exception::kSuccess};
}
NEARBY_LOGS(INFO) << "Multiplex: Closing physical socket: " << this;
return impl_->Close();
}
// Returns true if this is a virtual socket.
bool IsVirtualSocket() override { return is_virtual_socket_; }
// Creates a virtual socket only with outputstream.
MediumSocket* CreateVirtualSocket(OutputStream* outputstream) override;
MediumSocket* CreateVirtualSocket(
const std::string& salted_service_id_hash_key, OutputStream* outputstream,
location::nearby::proto::connections::Medium medium,
absl::flat_hash_map<std::string, std::shared_ptr<MediumSocket>>*
virtual_sockets_ptr) override;
/** Feeds the received incoming data to the client. */
void FeedIncomingData(ByteArray data) override {
if (!IsVirtualSocket()) {
NEARBY_LOGS(INFO) << "Feeding data on a physical socket is not allowed.";
return;
}
blocking_queue_input_stream_->Write(data);
}
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
BluetoothDevice GetRemoteDevice() {
@@ -73,7 +128,10 @@ class BluetoothSocket final {
// BluetoothServerSocket::Accept().
// These methods may also return an invalid socket if connection failed for
// any reason.
bool IsValid() const { return impl_ != nullptr; }
bool IsValid() const {
if (is_virtual_socket_) return true;
return impl_ != nullptr;
}
// Returns reference to platform implementation.
// This is used to communicate with platform code, and for debugging purposes.
@@ -84,6 +142,11 @@ class BluetoothSocket final {
private:
std::shared_ptr<api::BluetoothSocket> impl_;
absl::flat_hash_map<std::string, std::shared_ptr<MediumSocket>>*
virtual_sockets_ptr_ = nullptr;
std::shared_ptr<BlockingQueueStream> blocking_queue_input_stream_ = nullptr;
OutputStream* virtual_output_stream_ = nullptr;
bool is_virtual_socket_ = false;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
+14 -14
View File
@@ -129,7 +129,7 @@ TEST_P(BluetoothClassicMediumTest, CanConnectToService) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch, &discovered_device](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
@@ -178,7 +178,7 @@ TEST_P(BluetoothClassicMediumTest, CanCancelConnect) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch, &discovered_device](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
@@ -234,7 +234,7 @@ TEST_F(BluetoothClassicMediumTest, SendData) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch, &discovered_device](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
@@ -281,7 +281,7 @@ TEST_F(BluetoothClassicMediumTest, IoOnClosedSocketReturnsEmpty) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch, &discovered_device](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
@@ -350,13 +350,13 @@ TEST_F(BluetoothClassicMediumTest, CanStartDiscovery) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
found_latch.CountDown();
},
.device_lost_cb =
[this, &lost_latch](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device lost: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device lost: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
lost_latch.CountDown();
},
@@ -379,13 +379,13 @@ TEST_F(BluetoothClassicMediumTest, CanStopDiscovery) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
found_latch.CountDown();
},
.device_lost_cb =
[this, &lost_latch](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device lost: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device lost: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
lost_latch.CountDown();
},
@@ -406,7 +406,7 @@ TEST_F(BluetoothClassicMediumTest, CanListenForService) {
bt_a_->StartDiscovery(DiscoveryCallback{
.device_discovered_cb =
[this, &found_latch](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
found_latch.CountDown();
},
@@ -435,7 +435,7 @@ TEST_F(BluetoothClassicMediumTest, BluetoothPairingSuccess) {
CountDownLatch found_latch(1);
bt_a_->StartDiscovery(
DiscoveryCallback{.device_discovered_cb = [&](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
@@ -507,7 +507,7 @@ TEST_F(BluetoothClassicMediumTest, BluetoothPairingFailure) {
CountDownLatch found_latch(1);
bt_a_->StartDiscovery(
DiscoveryCallback{.device_discovered_cb = [&](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
@@ -569,9 +569,9 @@ TEST_F(BluetoothClassicMediumTest, CancelBluetoothPairing) {
CountDownLatch found_latch(1);
bt_a_->StartDiscovery(
DiscoveryCallback{.device_discovered_cb = [&](BluetoothDevice& device) {
NEARBY_LOG(INFO, "Device discovered: %s", device.GetName().c_str());
NEARBY_LOG(INFO, "Device discovered address: %s",
device.GetMacAddress().c_str());
NEARBY_LOGS(INFO) << "Device discovered: " << device.GetName();
NEARBY_LOGS(INFO) << "Device discovered address: "
<< device.GetMacAddress();
EXPECT_EQ(device.GetName(), adapter_b_->GetName());
discovered_device = &device;
found_latch.CountDown();
+6
View File
@@ -15,9 +15,15 @@
#include "internal/platform/bluetooth_utils.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "internal/platform/byte_array.h"
namespace nearby {
+3
View File
@@ -15,6 +15,9 @@
#ifndef PLATFORM_BASE_BLUETOOTH_UTILS_H_
#define PLATFORM_BASE_BLUETOOTH_UTILS_H_
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
#include "internal/platform/byte_array.h"
-7
View File
@@ -37,14 +37,7 @@
#include <memory>
#include <utility>
#ifdef NEARBY_CHROMIUM
#include "base/check.h"
#elif defined(NEARBY_SWIFTPM)
#include "internal/platform/logging.h"
#else
#include "absl/log/check.h" // nogncheck
#endif
#include "internal/platform/mutex.h"
#include "internal/platform/mutex_lock.h"
+1
View File
@@ -24,6 +24,7 @@
#include <utility>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace nearby {
+2
View File
@@ -15,9 +15,11 @@
#include "internal/platform/byte_utils.h"
#include <cstdlib>
#include <string>
#include "absl/strings/str_format.h"
#include "internal/platform/base_input_stream.h"
#include "internal/platform/byte_array.h"
namespace nearby {
+1
View File
@@ -15,6 +15,7 @@
#ifndef PLATFORM_BASE_BYTE_UTILS_H_
#define PLATFORM_BASE_BYTE_UTILS_H_
#include <string>
#include "internal/platform/byte_array.h"
namespace nearby {
+12 -9
View File
@@ -14,8 +14,8 @@
#include "internal/platform/condition_variable.h"
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include <cstdint>
#include "gtest/gtest.h"
#include "absl/time/time.h"
#include "internal/platform/logging.h"
@@ -25,6 +25,7 @@
namespace nearby {
namespace {
constexpr absl::Duration kWaitTime = absl::Milliseconds(500);
TEST(ConditionVariableTest, CanCreate) {
Mutex mutex;
@@ -36,17 +37,17 @@ TEST(ConditionVariableTest, CanWakeupWaiter) {
ConditionVariable cond{&mutex};
bool done = false;
bool waiting = false;
NEARBY_LOG(INFO, "At start; done=%d", done);
NEARBY_LOGS(INFO) << "At start; done=" << done;
{
SingleThreadExecutor executor;
executor.Execute([&cond, &mutex, &done, &waiting]() {
MutexLock lock(&mutex);
NEARBY_LOG(INFO, "Before cond.Wait(); done=%d", done);
NEARBY_LOGS(INFO) << "Before cond.Wait(); done=" << done;
waiting = true;
cond.Wait();
waiting = false;
done = true;
NEARBY_LOG(INFO, "After cond.Wait(); done=%d", done);
NEARBY_LOGS(INFO) << "After cond.Wait(); done=" << done;
});
while (true) {
{
@@ -61,7 +62,7 @@ TEST(ConditionVariableTest, CanWakeupWaiter) {
EXPECT_FALSE(done);
}
}
NEARBY_LOG(INFO, "After executor shutdown: done=%d", done);
NEARBY_LOGS(INFO) << "After executor shutdown: done=" << done;
EXPECT_TRUE(done);
}
@@ -70,11 +71,13 @@ TEST(ConditionVariableTest, WaitTerminatesOnTimeoutWithoutNotify) {
ConditionVariable cond{&mutex};
MutexLock lock(&mutex);
const absl::Duration kWaitTime = absl::Milliseconds(100);
absl::Time start = SystemClock::ElapsedRealtime();
cond.Wait(kWaitTime);
absl::Duration duration = SystemClock::ElapsedRealtime() - start;
EXPECT_GE(duration, kWaitTime);
int64_t bias = absl::ToInt64Milliseconds(SystemClock::ElapsedRealtime() -
start - kWaitTime);
// Windows cannot guarantee the exact time of the timeout.
EXPECT_GE(bias, -100);
}
} // namespace
@@ -14,10 +14,7 @@
#include "internal/platform/credential_storage_impl.h"
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
@@ -25,6 +22,7 @@
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/credential_callbacks.h"
#include "internal/proto/credential.pb.h"
@@ -67,19 +65,19 @@ SharedCredential CreatePublicCredential(absl::string_view secret_id,
std::vector<LocalCredential> BuildPrivateCreds(absl::string_view secret_id) {
std::vector<LocalCredential> private_credentials = {
CreateLocalCredential(secret_id, IdentityType::IDENTITY_TYPE_PRIVATE),
CreateLocalCredential(secret_id, IdentityType::IDENTITY_TYPE_TRUSTED),
CreateLocalCredential(secret_id,
IdentityType::IDENTITY_TYPE_PROVISIONED)};
IdentityType::IDENTITY_TYPE_PRIVATE_GROUP),
CreateLocalCredential(secret_id,
IdentityType::IDENTITY_TYPE_CONTACTS_GROUP)};
return private_credentials;
}
std::vector<SharedCredential> BuildPublicCreds(absl::string_view secret_id) {
std::vector<SharedCredential> public_credentials = {
CreatePublicCredential(secret_id, IdentityType::IDENTITY_TYPE_PRIVATE),
CreatePublicCredential(secret_id, IdentityType::IDENTITY_TYPE_TRUSTED),
CreatePublicCredential(secret_id,
IdentityType::IDENTITY_TYPE_PROVISIONED)};
IdentityType::IDENTITY_TYPE_PRIVATE_GROUP),
CreatePublicCredential(secret_id,
IdentityType::IDENTITY_TYPE_CONTACTS_GROUP)};
return public_credentials;
}
@@ -450,9 +448,10 @@ TEST_P(IdentityFilterTest, FilterLocalCredentialsByIdentityType) {
TEST_P(IdentityFilterTest, FilterLocalCredentialsFailsWhenNoCredentialsMatch) {
IdentityType identity_type = GetParam();
// Create a credential of a different identity type than the one we query.
IdentityType other_type = identity_type == IdentityType::IDENTITY_TYPE_PRIVATE
? IdentityType::IDENTITY_TYPE_TRUSTED
: IdentityType::IDENTITY_TYPE_PRIVATE;
IdentityType other_type =
identity_type == IdentityType::IDENTITY_TYPE_PRIVATE_GROUP
? IdentityType::IDENTITY_TYPE_CONTACTS_GROUP
: IdentityType::IDENTITY_TYPE_PRIVATE_GROUP;
std::vector<LocalCredential> private_creds = {
CreateLocalCredential(kSecretId, other_type)};
CredentialStorageImpl credential_storage;
@@ -486,9 +485,10 @@ TEST_P(IdentityFilterTest, FilterPublicCredentialsByIdentityType) {
TEST_P(IdentityFilterTest, FilterPublicCredentialsFailsWhenNoCredentialsMatch) {
IdentityType identity_type = GetParam();
// Create a credential of a different identity type than the one we query.
IdentityType other_type = identity_type == IdentityType::IDENTITY_TYPE_PRIVATE
? IdentityType::IDENTITY_TYPE_TRUSTED
: IdentityType::IDENTITY_TYPE_PRIVATE;
IdentityType other_type =
identity_type == IdentityType::IDENTITY_TYPE_PRIVATE_GROUP
? IdentityType::IDENTITY_TYPE_CONTACTS_GROUP
: IdentityType::IDENTITY_TYPE_PRIVATE_GROUP;
std::vector<SharedCredential> public_creds = {
CreatePublicCredential(kSecretId, other_type)};
CredentialStorageImpl credential_storage;
@@ -503,9 +503,8 @@ TEST_P(IdentityFilterTest, FilterPublicCredentialsFailsWhenNoCredentialsMatch) {
INSTANTIATE_TEST_SUITE_P(
CredentialStorageImplTest, IdentityFilterTest,
testing::Values(IdentityType::IDENTITY_TYPE_PRIVATE,
IdentityType::IDENTITY_TYPE_TRUSTED,
IdentityType::IDENTITY_TYPE_PROVISIONED));
testing::Values(IdentityType::IDENTITY_TYPE_PRIVATE_GROUP,
IdentityType::IDENTITY_TYPE_CONTACTS_GROUP));
} // namespace
} // namespace nearby
+1 -1
View File
@@ -15,6 +15,6 @@
#ifndef PLATFORM_PUBLIC_CRYPTO_H_
#define PLATFORM_PUBLIC_CRYPTO_H_
#include "internal/platform/implementation/crypto.h"
#include "internal/platform/implementation/crypto.h" // IWYU pragma: export
#endif // PLATFORM_PUBLIC_CRYPTO_H_
+46
View File
@@ -14,12 +14,29 @@
#include "internal/platform/crypto.h"
#include <stddef.h>
#include <cstdint>
#include <string>
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
#include "internal/crypto_cros/nearby_base.h"
#include "internal/platform/byte_array.h"
namespace nearby {
namespace {
// Ensures we don't have all trivial data, i.e. that the data is indeed random.
// Currently, that means the bytes cannot be all the same (e.g. all zeros).
bool IsTrivial(const std::string& bytes) {
for (size_t i = 0; i < bytes.size(); i++) {
if (bytes[i] != bytes[0]) {
return false;
}
}
return true;
}
TEST(CryptoTest, Md5GeneratesHash) {
const ByteArray expected_md5(
@@ -44,4 +61,33 @@ TEST(CryptoTest, Sha256ReturnsEmptyOnError) {
EXPECT_EQ(Crypto::Sha256(""), ByteArray{});
}
// Basic functionality tests. Does NOT test the security of the random data.
TEST(CryptoTest, RandBytes) {
std::string bytes(16, '\0');
RandBytes(nearbybase::WriteInto(&bytes, bytes.size()), bytes.size());
EXPECT_TRUE(!IsTrivial(bytes));
}
TEST(CryptoTest, RandomString) {
constexpr size_t kSize = 30;
std::string bytes(kSize, 0);
RandBytes(const_cast<std::string::value_type*>(bytes.data()), bytes.size());
EXPECT_EQ(bytes.size(), kSize);
EXPECT_TRUE(!IsTrivial(bytes));
}
TEST(CryptoTest, RandData) {
uint64_t x = nearby::RandData<uint64_t>();
uint64_t y = nearby::RandData<uint64_t>();
// Once in a billion years, consecutively generated random numbers will be
// the same and the test will fail.
EXPECT_NE(x, y);
EXPECT_NE(x >> 32, x & 0xFFFFFFFF);
}
} // namespace
} // namespace nearby
+12 -13
View File
@@ -15,14 +15,14 @@
#ifndef PLATFORM_PUBLIC_DEVICE_INFO_H_
#define PLATFORM_PUBLIC_DEVICE_INFO_H_
#include <filesystem>
#include <cstddef>
#include <filesystem> // NOLINT
#include <functional>
#include <optional>
#include <string>
#include "absl/strings/string_view.h"
#include "internal/platform/implementation/device_info.h"
#include "internal/platform/implementation/platform.h"
namespace nearby {
@@ -30,17 +30,16 @@ class DeviceInfo {
public:
virtual ~DeviceInfo() = default;
virtual std::u16string GetOsDeviceName() const = 0;
// All strings are UTF-8 encoded.
virtual std::string GetOsDeviceName() const = 0;
virtual api::DeviceInfo::DeviceType GetDeviceType() const = 0;
virtual api::DeviceInfo::OsType GetOsType() const = 0;
virtual std::optional<std::u16string> GetFullName() const = 0;
virtual std::optional<std::u16string> GetGivenName() const = 0;
virtual std::optional<std::u16string> GetLastName() const = 0;
virtual std::optional<std::string> GetProfileUserName() const = 0;
virtual std::optional<std::string> GetGivenName() const = 0;
virtual std::filesystem::path GetDownloadPath() const = 0;
virtual std::filesystem::path GetAppDataPath() const = 0;
virtual std::filesystem::path GetTemporaryPath() const = 0;
virtual std::filesystem::path GetLogPath() const = 0;
virtual std::optional<size_t> GetAvailableDiskSpaceInBytes(
const std::filesystem::path& path) const = 0;
@@ -55,18 +54,18 @@ class DeviceInfo {
virtual bool PreventSleep() = 0;
virtual bool AllowSleep() = 0;
// Returns localized device name depends on device type.
std::u16string GetDeviceTypeName() const {
// Returns UTF-8 encoded localized device name depending on device type.
std::string GetDeviceTypeName() const {
// TODO(b/230132370): return localized device name.
switch (GetDeviceType()) {
case api::DeviceInfo::DeviceType::kPhone:
return u"Phone";
return "Phone";
case api::DeviceInfo::DeviceType::kTablet:
return u"Tablet";
return "Tablet";
case api::DeviceInfo::DeviceType::kLaptop:
return u"PC";
return "PC";
default:
return u"Unknown";
return "Unknown";
}
}
};

Some files were not shown because too many files have changed in this diff Show More