Roll forward to cl/338482889

Signed-off-by: Alexey Polyudov <apolyudov@google.com>
Change-Id: I9850950db8bd84f0904ea1a413151887f52098cf
This commit is contained in:
Alexey Polyudov
2020-10-22 10:47:34 -07:00
parent d68e53cf03
commit 2155b3ddeb
542 changed files with 15219 additions and 42295 deletions
+379 -373
View File
@@ -2,432 +2,443 @@
#define CORE_INTERNAL_BASE_PCP_HANDLER_H_
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "core/internal/bandwidth_upgrade_manager.h"
#include "core/internal/bwu_manager.h"
#include "core/internal/client_proxy.h"
#include "core/internal/encryption_runner.h"
#include "core/internal/endpoint_channel_manager.h"
#include "core/internal/endpoint_manager.h"
#include "core/internal/mediums/mediums.h"
#include "core/internal/mediums/webrtc.h"
#include "core/internal/pcp.h"
#include "core/internal/pcp_handler.h"
#include "core/listeners.h"
#include "core/options.h"
#include "core/status.h"
#include "proto/connections/offline_wire_formats.pb.h"
#include "platform/api/atomic_reference.h"
#include "platform/api/count_down_latch.h"
#include "platform/api/settable_future.h"
#include "platform/api/system_clock.h"
#include "platform/cancelable_alarm.h"
#include "platform/port/string.h"
#include "platform/prng.h"
#include "platform/ptr.h"
#include "platform/base/byte_array.h"
#include "platform/base/prng.h"
#include "platform/public/atomic_boolean.h"
#include "platform/public/atomic_reference.h"
#include "platform/public/cancelable_alarm.h"
#include "platform/public/count_down_latch.h"
#include "platform/public/future.h"
#include "platform/public/scheduled_executor.h"
#include "platform/public/single_thread_executor.h"
#include "platform/public/system_clock.h"
#include "proto/connections_enums.pb.h"
#include "securegcm/d2d_connection_context_v1.h"
#include "securegcm/ukey2_handshake.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_map.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
namespace connections {
namespace base_pcp_handler {
// Define a class that supports move operation for pointers using std::swap.
// It replicates std::unique_ptr<> behavior, but it does not own the pointer,
// so it does not attempt destroy it.
// This approach was recommended during code review, as a better alternative to
// reuse of std::unique_ptr<> with custom no-op deleter, for the sake of
// readability.
template <typename T>
class Swapper {
public:
Swapper(T* pointer) : pointer_(pointer) {} // NOLINT.
Swapper(Swapper&& other) { *this = std::move(other); }
Swapper& operator=(Swapper&& other) {
std::swap(pointer_, other.pointer_);
return *this;
}
T* operator->() const { return pointer_; }
T& operator*() { return *pointer_; }
operator T*() { return pointer_; } // NOLINT.
T* get() const { return pointer_; }
void reset() { pointer_ = nullptr; }
template <typename>
class StartAdvertisingCallable;
template <typename>
class StopAdvertisingRunnable;
template <typename>
class StartDiscoveryCallable;
template <typename>
class StopDiscoveryRunnable;
template <typename>
class RequestConnectionRunnable;
template <typename>
class AcceptConnectionCallable;
template <typename>
class RejectConnectionCallable;
template <typename>
class ProcessEndpointDisconnectionRunnable;
template <typename>
class OnConnectionResponseRunnable;
template <typename>
class OnEncryptionSuccessRunnable;
template <typename>
class OnEncryptionFailureRunnable;
private:
T* pointer_ = nullptr;
};
} // namespace base_pcp_handler
template <typename T>
Swapper<T> MakeSwapper(T* value) {
return Swapper<T>(value);
}
// A base implementation of the PCPHandler interface that takes care of all
// bookkeeping and handshake protocols that are common across all PCPHandler
// implementations -- thus, every concrete PCPHandler implementation must extend
// Represents the WebRtc state that mediums are connectable or not.
enum class WebRtcState {
kUndefined = 0,
kConnectable = 1,
kUnconnectable = 2,
};
// A base implementation of the PcpHandler interface that takes care of all
// bookkeeping and handshake protocols that are common across all PcpHandler
// implementations -- thus, every concrete PcpHandler implementation must extend
// this class, so that they can focus exclusively on the medium-specific
// operations.
template <typename Platform>
class BasePCPHandler
: public PCPHandler<Platform>,
public EndpointManager<Platform>::IncomingOfflineFrameProcessor {
class BasePcpHandler : public PcpHandler,
public EndpointManager::FrameProcessor {
public:
// TODO(tracyzhou): Add SecureRandom.
BasePCPHandler(Ptr<EndpointManager<Platform> > endpoint_manager,
Ptr<EndpointChannelManager> endpoint_channel_manager,
Ptr<BandwidthUpgradeManager> bandwidth_upgrade_manager);
~BasePCPHandler() override;
using FrameProcessor = EndpointManager::FrameProcessor;
// We have been asked by the client to start advertising. Once we successfully
// start advertising, we'll change the ClientProxy's state.
Status::Value startAdvertising(
Ptr<ClientProxy<Platform> > client_proxy, const string& service_id,
const string& local_endpoint_name,
const AdvertisingOptions& advertising_options,
Ptr<ConnectionLifecycleListener> connection_lifecycle_listener) override;
void stopAdvertising(Ptr<ClientProxy<Platform> > client_proxy) override;
// TODO(apolyudov): Add SecureRandom.
BasePcpHandler(Mediums* mediums, EndpointManager* endpoint_manager,
EndpointChannelManager* channel_manager,
BwuManager* bwu_manager, Pcp pcp);
~BasePcpHandler() override;
BasePcpHandler(BasePcpHandler&&) = delete;
BasePcpHandler& operator=(BasePcpHandler&&) = delete;
Status::Value startDiscovery(
Ptr<ClientProxy<Platform> > client_proxy, const string& service_id,
const DiscoveryOptions& discovery_options,
Ptr<DiscoveryListener> discovery_listener) override;
void stopDiscovery(Ptr<ClientProxy<Platform> > client_proxy) override;
// Starts advertising. Once successfully started, changes ClientProxy's state.
// Notifies ConnectionListener (info.listener) in case of any event.
// See
// https://source.corp.google.com/piper///depot/google3/core/listeners.h;l=78
Status StartAdvertising(ClientProxy* client, const std::string& service_id,
const ConnectionOptions& options,
const ConnectionRequestInfo& info) override;
Status::Value requestConnection(
Ptr<ClientProxy<Platform> > client_proxy, const string& endpoint_name,
const string& endpoint_id,
Ptr<ConnectionLifecycleListener> connection_lifecycle_listener) override;
Status::Value acceptConnection(
Ptr<ClientProxy<Platform> > client_proxy, const string& endpoint_id,
Ptr<PayloadListener> payload_listener) override;
Status::Value rejectConnection(Ptr<ClientProxy<Platform> > client_proxy,
const string& endpoint_id) override;
// Stops Advertising is active, and changes CLientProxy state,
// otherwise does nothing.
void StopAdvertising(ClientProxy* client) override;
proto::connections::Medium getBandwidthUpgradeMedium() override;
// Starts discovery of endpoints that may be advertising.
// Updates ClientProxy state once discovery started.
// DiscoveryListener will get called in case of any event.
Status StartDiscovery(ClientProxy* client, const std::string& service_id,
const ConnectionOptions& options,
const DiscoveryListener& listener) override;
// Stops Discovery if it is active, and changes CLientProxy state,
// otherwise does nothing.
void StopDiscovery(ClientProxy* client) override;
void InjectEndpoint(ClientProxy* client,
const std::string& service_id,
const OutOfBandConnectionMetadata& metadata) override;
// Requests a newly discovered remote endpoint it to form a connection.
// Updates state on ClientProxy.
Status RequestConnection(ClientProxy* client, const std::string& endpoint_id,
const ConnectionRequestInfo& info,
const ConnectionOptions& options) override;
// Called by either party to accept connection on their part.
// Until both parties call it, connection will not reach a data phase.
// Updates state in ClientProxy.
Status AcceptConnection(ClientProxy* client, const std::string& endpoint_id,
const PayloadListener& payload_listener) override;
// Called by either party to reject connection on their part.
// If either party does call it, connection will terminate.
// Updates state in ClientProxy.
Status RejectConnection(ClientProxy* client,
const std::string& endpoint_id) override;
// @EndpointManagerReaderThread
void processIncomingOfflineFrame(
ConstPtr<OfflineFrame> offline_frame, const string& from_endpoint_id,
Ptr<ClientProxy<Platform> > to_client_proxy,
proto::connections::Medium current_medium) override;
void OnIncomingFrame(OfflineFrame& frame, const std::string& endpoint_id,
ClientProxy* client,
proto::connections::Medium medium) override;
// Called when an endpoint disconnects while we're waiting for both sides to
// approve/reject the connection.
// @EndpointManagerThread
void processEndpointDisconnection(
Ptr<ClientProxy<Platform> > client_proxy, const string& endpoint_id,
Ptr<CountDownLatch> process_disconnection_barrier) override;
void OnEndpointDisconnect(ClientProxy* client, const std::string& endpoint_id,
CountDownLatch* barrier) override;
// Conforms to EncryptionRunner::ResultListener::onEncryptionSuccess().
// @EncryptionRunnerThread
void onEncryptionSuccessImpl(const string& endpoint_id,
Ptr<securegcm::UKey2Handshake> ukey2_handshake,
const string& authentication_token,
ConstPtr<ByteArray> raw_authentication_token);
// EncryptionRunner::ResultListener::onEncryptionFailure().
// @EncryptionRunnerThread
void onEncryptionFailureImpl(const string& endpoint_id,
Ptr<EndpointChannel> channel);
Pcp GetPcp() const override { return pcp_; }
Strategy GetStrategy() const override { return strategy_; }
Medium GetBwuMedium() const { return bwu_medium_.Get(); }
void DisconnectFromEndpointManager();
protected:
// The result of a call to startAdvertisingImpl() or startDiscoveryImpl().
class StartOperationResult {
public:
static Ptr<StartOperationResult> error(Status::Value status) {
return MakePtr(new StartOperationResult(status));
}
static Ptr<StartOperationResult> success(
const std::vector<proto::connections::Medium>& mediums) {
// Note: check here and not in the constructor, since for errors we have
// null mediums.
return MakePtr(new StartOperationResult(mediums));
}
private:
template <typename>
friend class base_pcp_handler::StartAdvertisingCallable;
template <typename>
friend class base_pcp_handler::StartDiscoveryCallable;
explicit StartOperationResult(Status::Value status)
: status_(status), mediums_() {}
explicit StartOperationResult(
const std::vector<proto::connections::Medium>& mediums)
: status_(Status::SUCCESS), mediums_(mediums) {}
// The status to be returned to the client.
Status::Value status_;
struct StartOperationResult {
Status status;
// If success, the mediums on which we are now advertising/discovering, for
// analytics.
std::vector<proto::connections::Medium> mediums_;
std::vector<proto::connections::Medium> mediums;
};
// Represents an endpoint that we've discovered. Typically, the implementation
// will know how to connect to this endpoint if asked. (eg. It holds on to a
// BluetoothDevice)
class DiscoveredEndpoint {
public:
virtual ~DiscoveredEndpoint() {}
//
// NOTE(DiscoveredEndpoint):
// Specific protocol is expected to derive from it, as follows:
// struct ProtocolEndpoint : public DiscoveredEndpoint {
// ProtocolContext context;
// };
// Protocol then allocates instance with std::make_shared<ProtocolEndpoint>(),
// and passes this instance to OnEndpointFound() method.
// When calling OnEndpointLost(), protocol does not need to pass the same
// instance (but it can if implementation desires to do so).
// BasePcpHandler will hold on to the shared_ptr<DiscoveredEndpoint>.
struct DiscoveredEndpoint {
DiscoveredEndpoint(std::string endpoint_id, ByteArray endpoint_info,
std::string service_id,
proto::connections::Medium medium,
WebRtcState web_rtc_state)
: endpoint_id(std::move(endpoint_id)),
endpoint_info(std::move(endpoint_info)),
service_id(std::move(service_id)),
medium(medium),
web_rtc_state(web_rtc_state) {}
virtual ~DiscoveredEndpoint() = default;
virtual string getEndpointId() = 0;
virtual string getEndpointName() = 0;
virtual string getServiceId() = 0;
virtual proto::connections::Medium getMedium() = 0;
std::string endpoint_id;
ByteArray endpoint_info;
std::string service_id;
proto::connections::Medium medium;
WebRtcState web_rtc_state;
};
struct BluetoothEndpoint : public DiscoveredEndpoint {
BluetoothEndpoint(DiscoveredEndpoint endpoint, BluetoothDevice device)
: DiscoveredEndpoint(std::move(endpoint)),
bluetooth_device(std::move(device)) {}
BluetoothDevice bluetooth_device;
};
struct WifiLanEndpoint : public DiscoveredEndpoint {
WifiLanEndpoint(DiscoveredEndpoint endpoint, WifiLanService service)
: DiscoveredEndpoint(std::move(endpoint)),
wifi_lan_service(std::move(service)) {}
WifiLanService wifi_lan_service;
};
struct WebRtcEndpoint : public DiscoveredEndpoint {
WebRtcEndpoint(DiscoveredEndpoint endpoint, mediums::PeerId peer_id)
: DiscoveredEndpoint(std::move(endpoint)),
peer_id(std::move(peer_id)) {}
mediums::PeerId peer_id;
};
struct ConnectImplResult {
proto::connections::Medium medium;
Status::Value status;
Ptr<EndpointChannel> endpoint_channel;
explicit ConnectImplResult(Ptr<EndpointChannel> endpoint_channel)
: medium(proto::connections::Medium::UNKNOWN_MEDIUM),
status(Status::SUCCESS),
endpoint_channel(endpoint_channel) {}
ConnectImplResult(proto::connections::Medium medium, Status::Value status)
: medium(medium), status(status), endpoint_channel() {}
proto::connections::Medium medium =
proto::connections::Medium::UNKNOWN_MEDIUM;
Status status = {Status::kError};
std::unique_ptr<EndpointChannel> endpoint_channel;
};
void runOnPCPHandlerThread(Ptr<Runnable> runnable);
void RunOnPcpHandlerThread(Runnable runnable);
Ptr<AdvertisingOptions> getAdvertisingOptions();
BluetoothDevice GetRemoteBluetoothDevice(
const std::string& remote_bluetooth_mac_address);
// @PCPHandlerThread
void onEndpointFound(Ptr<ClientProxy<Platform> > client_proxy,
Ptr<DiscoveredEndpoint> endpoint);
ConnectionOptions GetConnectionOptions() const;
ConnectionOptions GetDiscoveryOptions() const;
// @PCPHandlerThread
void onEndpointLost(Ptr<ClientProxy<Platform> > client_proxy,
Ptr<DiscoveredEndpoint> endpoint);
// @PcpHandlerThread
void OnEndpointFound(ClientProxy* client,
std::shared_ptr<DiscoveredEndpoint> endpoint);
Exception::Value onIncomingConnection(
Ptr<ClientProxy<Platform> > client_proxy,
const string& remote_device_name, Ptr<EndpointChannel> endpoint_channel,
// @PcpHandlerThread
void OnEndpointLost(ClientProxy* client, const DiscoveredEndpoint& endpoint);
Exception OnIncomingConnection(
ClientProxy* client, const ByteArray& remote_endpoint_info,
std::unique_ptr<EndpointChannel> endpoint_channel,
proto::connections::Medium medium); // throws Exception::IO
virtual bool hasOutgoingConnections(Ptr<ClientProxy<Platform> > client_proxy);
virtual bool hasIncomingConnections(Ptr<ClientProxy<Platform> > client_proxy);
virtual bool HasOutgoingConnections(ClientProxy* client) const;
virtual bool HasIncomingConnections(ClientProxy* client) const;
virtual bool canSendOutgoingConnection(
Ptr<ClientProxy<Platform> > client_proxy);
virtual bool canReceiveIncomingConnection(
Ptr<ClientProxy<Platform> > client_proxy);
virtual bool CanSendOutgoingConnection(ClientProxy* client) const;
virtual bool CanReceiveIncomingConnection(ClientProxy* client) const;
// @PCPHandlerThread
virtual Ptr<StartOperationResult> startAdvertisingImpl(
Ptr<ClientProxy<Platform> > client_proxy, const string& service_id,
const string& local_endpoint_id, const string& local_endpoint_name,
const AdvertisingOptions& options) = 0;
// @PCPHandlerThread
virtual Status::Value stopAdvertisingImpl(
Ptr<ClientProxy<Platform> > client_proxy) = 0;
// @PcpHandlerThread
virtual StartOperationResult StartAdvertisingImpl(
ClientProxy* client, const std::string& service_id,
const std::string& local_endpoint_id,
const ByteArray& local_endpoint_info,
const ConnectionOptions& options) = 0;
// @PcpHandlerThread
virtual Status StopAdvertisingImpl(ClientProxy* client) = 0;
// @PCPHandlerThread
virtual Ptr<StartOperationResult> startDiscoveryImpl(
Ptr<ClientProxy<Platform> > client_proxy, const string& service_id,
const DiscoveryOptions& options) = 0;
// @PCPHandlerThread
virtual Status::Value stopDiscoveryImpl(
Ptr<ClientProxy<Platform> > client_proxy) = 0;
// @PcpHandlerThread
virtual StartOperationResult StartDiscoveryImpl(
ClientProxy* client, const std::string& service_id,
const ConnectionOptions& options) = 0;
// @PcpHandlerThread
virtual Status StopDiscoveryImpl(ClientProxy* client) = 0;
// @PCPHandlerThread
virtual ConnectImplResult connectImpl(
Ptr<ClientProxy<Platform> > client_proxy,
Ptr<DiscoveredEndpoint> endpoint) = 0;
// @PcpHandlerThread
virtual Status InjectEndpointImpl(
ClientProxy* client,
const std::string& service_id,
const OutOfBandConnectionMetadata& metadata) = 0;
// @PcpHandlerThread
virtual ConnectImplResult ConnectImpl(ClientProxy* client,
DiscoveredEndpoint* endpoint) = 0;
virtual std::vector<proto::connections::Medium>
getConnectionMediumsByPriority() = 0;
virtual proto::connections::Medium getDefaultUpgradeMedium() = 0;
GetConnectionMediumsByPriority() = 0;
virtual proto::connections::Medium GetDefaultUpgradeMedium() = 0;
Ptr<EndpointManager<Platform> > endpoint_manager_;
Ptr<EndpointChannelManager> endpoint_channel_manager_;
Ptr<BandwidthUpgradeManager> bandwidth_upgrade_manager_;
// Returns the first discovered endpoint for the given endpoint_id.
DiscoveredEndpoint* GetDiscoveredEndpoint(const std::string& endpoint_id);
// Returns a vector of discovered endpoints, sorted in order of decreasing
// preference.
std::vector<BasePcpHandler::DiscoveredEndpoint*> GetDiscoveredEndpoints(
const std::string& endpoint_id);
mediums::PeerId CreatePeerIdFromAdvertisement(const string& service_id,
const string& endpoint_id,
const ByteArray& endpoint_info);
Mediums* mediums_;
EndpointManager* endpoint_manager_;
EndpointChannelManager* channel_manager_;
private:
template <typename>
friend class base_pcp_handler::StartAdvertisingCallable;
template <typename>
friend class base_pcp_handler::StopAdvertisingRunnable;
template <typename>
friend class base_pcp_handler::StartDiscoveryCallable;
template <typename>
friend class base_pcp_handler::StopDiscoveryRunnable;
template <typename>
friend class base_pcp_handler::RequestConnectionRunnable;
template <typename>
friend class base_pcp_handler::AcceptConnectionCallable;
template <typename>
friend class base_pcp_handler::RejectConnectionCallable;
template <typename>
friend class base_pcp_handler::OnConnectionResponseRunnable;
template <typename>
friend class base_pcp_handler::ProcessEndpointDisconnectionRunnable;
template <typename>
friend class base_pcp_handler::OnEncryptionSuccessRunnable;
template <typename>
friend class base_pcp_handler::OnEncryptionFailureRunnable;
class ResultListenerFacade
: public EncryptionRunner<Platform>::ResultListener {
public:
explicit ResultListenerFacade(Ptr<BasePCPHandler<Platform> > impl)
: impl_(impl) {}
void onEncryptionSuccess(
const string& endpoint_id,
Ptr<securegcm::UKey2Handshake> ukey2_handshake,
const string& authentication_token,
ConstPtr<ByteArray> raw_authentication_token) override {
impl_->onEncryptionSuccessImpl(endpoint_id, ukey2_handshake,
authentication_token,
raw_authentication_token);
}
void onEncryptionFailure(const string& endpoint_id,
Ptr<EndpointChannel> channel) override {
impl_->onEncryptionFailureImpl(endpoint_id, channel);
}
private:
Ptr<BasePCPHandler<Platform> > impl_;
};
class PendingConnectionInfo {
public:
static Ptr<PendingConnectionInfo> newIncomingPendingConnectionInfo(
Ptr<ClientProxy<Platform> > client_proxy,
const string& remote_endpoint_name,
Ptr<EndpointChannel> endpoint_channel, std::int32_t nonce,
std::int64_t start_time_millis,
Ptr<ConnectionLifecycleListener> connection_lifecycle_listener,
const std::vector<proto::connections::Medium>& supported_mediums);
static Ptr<PendingConnectionInfo> newOutgoingPendingConnectionInfo(
Ptr<ClientProxy<Platform> > client_proxy,
const string& remote_endpoint_name,
Ptr<EndpointChannel> endpoint_channel, std::int32_t nonce,
std::int64_t start_time_millis,
Ptr<ConnectionLifecycleListener> connection_lifecycle_listener,
Ptr<SettableFuture<Status::Value> > request_connection_result);
struct PendingConnectionInfo {
PendingConnectionInfo() = default;
PendingConnectionInfo(PendingConnectionInfo&& other) = default;
PendingConnectionInfo& operator=(PendingConnectionInfo&&) = default;
~PendingConnectionInfo();
void setUKey2Handshake(Ptr<securegcm::UKey2Handshake> ukey2_handshake);
// Passes crypto context that we acquired in DH session for temporary
// ownership here.
void SetCryptoContext(std::unique_ptr<securegcm::UKey2Handshake> ukey2);
void localEndpointAcceptedConnection(const string& endpoint_id,
Ptr<PayloadListener> payload_listener);
// Pass Accept notification to client.
void LocalEndpointAcceptedConnection(
const std::string& endpoint_id,
const PayloadListener& payload_listener);
void localEndpointRejectedConnection(const string& endpoint_id);
// Pass Reject notification to client.
void LocalEndpointRejectedConnection(const std::string& endpoint_id);
private:
template <typename>
friend class BasePCPHandler;
template <typename>
friend class base_pcp_handler::RequestConnectionRunnable;
template <typename>
friend class base_pcp_handler::AcceptConnectionCallable;
template <typename>
friend class base_pcp_handler::RejectConnectionCallable;
template <typename>
friend class base_pcp_handler::OnEncryptionSuccessRunnable;
template <typename>
friend class base_pcp_handler::OnEncryptionFailureRunnable;
// Client state tracker to report events to. Never changes. Always valid.
ClientProxy* client = nullptr;
// Peer endpoint info, or empty, if not discovered yet. May change.
ByteArray remote_endpoint_info;
std::int32_t nonce = 0;
bool is_incoming = false;
absl::Time start_time{absl::InfinitePast()};
// Client callbacks. Always valid.
ConnectionListener listener;
ConnectionOptions options;
PendingConnectionInfo(
Ptr<ClientProxy<Platform> > client_proxy,
const string& remote_endpoint_name,
Ptr<EndpointChannel> endpoint_channel, std::int32_t nonce,
bool is_incoming, std::int64_t start_time_millis,
Ptr<ConnectionLifecycleListener> connection_lifecycle_listener,
Ptr<SettableFuture<Status::Value> > request_connection_result,
const std::vector<proto::connections::Medium>& supported_mediums);
// Only set for outgoing connections. If set, we must call
// result->Set() when connection is established, or rejected.
Swapper<Future<Status>> result = nullptr;
Ptr<ClientProxy<Platform> > client_proxy_;
const string remote_endpoint_name_;
// Can be released prior to destructor.
ScopedPtr<Ptr<EndpointChannel> > endpoint_channel_;
const std::int32_t nonce_;
const bool is_incoming_;
const std::int64_t start_time_millis_;
// Can be released prior to destructor.
ScopedPtr<Ptr<ConnectionLifecycleListener> > connection_lifecycle_listener_;
// Only (possibly) vector for incoming connections.
std::vector<proto::connections::Medium> supported_mediums;
// Only set for outgoing connections. Can be released prior to destructor.
// TODO(b/77783039): Consider creating a one-time-use-only wrapper class
// around the Ptr<SettableFuture> that's passed in (that also implements the
// SettableFuture interface) so we can avoid the easy-to-forget calls to
// request_connection_result_.clear() peppered through multiple places in
// the code.
Ptr<SettableFuture<Status::Value> > request_connection_result_;
// Keep track of a channel before we pass it to EndpointChannelManager.
std::unique_ptr<EndpointChannel> channel;
// Only (possibly) set for incoming connections.
const std::vector<proto::connections::Medium> supported_mediums_;
// If set, this is owned.
Ptr<securegcm::UKey2Handshake> ukey2_handshake_;
// Crypto context; initially empty; established first thing after channel
// creation by running UKey2 session. While it is in progress, we keep track
// of channel ourselves. Once it is done, we pass channel over to
// EndpointChannelManager. We keep crypto context until connection is
// accepted. Crypto context is passed over to channel_manager_ before
// switching to connected state, where Payload may be exchanged.
std::unique_ptr<securegcm::UKey2Handshake> ukey2;
};
static Exception::Value writeConnectionRequestFrame(
Ptr<EndpointChannel> endpoint_channel, const string& local_endpoint_id,
const string& local_endpoint_name, std::int32_t nonce,
// @EncryptionRunnerThread
// Called internally when DH session has negotiated a key successfully.
void OnEncryptionSuccessImpl(const std::string& endpoint_id,
std::unique_ptr<securegcm::UKey2Handshake> ukey2,
const std::string& auth_token,
const ByteArray& raw_auth_token);
// @EncryptionRunnerThread
// Called internally when DH session was not able to negotiate a key.
void OnEncryptionFailureImpl(const std::string& endpoint_id,
EndpointChannel* channel);
EncryptionRunner::ResultListener GetResultListener();
void OnEncryptionSuccessRunnable(
const std::string& endpoint_id,
std::unique_ptr<securegcm::UKey2Handshake> ukey2,
const std::string& auth_token, const ByteArray& raw_auth_token);
void OnEncryptionFailureRunnable(const std::string& endpoint_id,
EndpointChannel* endpoint_channel);
static Exception WriteConnectionRequestFrame(
EndpointChannel* endpoint_channel, const std::string& local_endpoint_id,
const ByteArray& local_endpoint_info, std::int32_t nonce,
const std::vector<proto::connections::Medium>& supported_mediums);
static const std::int64_t kConnectionRequestReadTimeoutMillis;
static const std::int64_t kRejectedConnectionCloseDelayMillis;
static constexpr absl::Duration kConnectionRequestReadTimeout =
absl::Seconds(2);
static constexpr absl::Duration kRejectedConnectionCloseDelay =
absl::Seconds(2);
template <typename T>
Ptr<Future<T> > runOnPCPHandlerThread(Ptr<Callable<T> > callable);
// The interface deviates from the Java code to convey a better ownership
// story. Ownership of 'connection_response_offline_frame' is transferred to
// the callee by calling this method.
void onConnectionResponse(
Ptr<ClientProxy<Platform> > client_proxy, const string& endpoint_id,
ConstPtr<OfflineFrame> connection_response_offline_frame);
void OnConnectionResponse(ClientProxy* client, const std::string& endpoint_id,
const OfflineFrame& frame);
// Returns true if the new endpoint is preferred over the old endpoint.
bool isPreferred(Ptr<DiscoveredEndpoint> new_endpoint,
Ptr<DiscoveredEndpoint> old_endpoint);
bool IsPreferred(const BasePcpHandler::DiscoveredEndpoint& new_endpoint,
const BasePcpHandler::DiscoveredEndpoint& old_endpoint);
bool shouldEnforceTopologyConstraints();
bool autoUpgradeBandwidth();
// Returns true, if connection party should respect the specified topology.
bool ShouldEnforceTopologyConstraints() const;
// Returns true if the incoming connection should be killed. This only happens
// when an incoming connection arrives while we have an outgoing connection to
// the same endpoint and we need to stop one connection.
bool breakTie(Ptr<ClientProxy<Platform> > client_proxy,
const string& endpoint_id, std::int32_t incoming_nonce,
Ptr<EndpointChannel> endpoint_channel);
// Returns true, if connection party should attempt to upgrade itself to
// use a higher bandwidth medium, if it is available.
bool AutoUpgradeBandwidth() const;
// Returns true if the incoming connection should be killed. This only
// happens when an incoming connection arrives while we have an outgoing
// connection to the same endpoint and we need to stop one connection.
bool BreakTie(ClientProxy* client, const std::string& endpoint_id,
std::int32_t incoming_nonce, EndpointChannel* channel);
// We're not sure how far our outgoing connection has gotten. We may (or may
// not) have called ClientProxy.onConnectionInitiated. Therefore, we'll call
// both preInit and preResult failures.
void processTieBreakLoss(Ptr<ClientProxy<Platform> > client_proxy,
const string& endpoint_id,
Ptr<PendingConnectionInfo> connection_info);
// not) have called ClientProxy::OnConnectionInitiated. Therefore, we'll
// call both preInit and preResult failures.
void ProcessTieBreakLoss(ClientProxy* client, const std::string& endpoint_id,
PendingConnectionInfo* info);
// Called when an incoming connection has been accepted by both sides.
//
// @param client_proxy The client
// @param endpoint_id The id of the remote device
// @param supported_mediums The mediums supported by the remote device. Empty
// @param supported_mediums The mediums supported by the remote device.
// Empty
// for outgoing connections and older devices that don't report their
// supported mediums.
void initiateBandwidthUpgrade(
Ptr<ClientProxy<Platform> > client_proxy, const string& endpoint_id,
void InitiateBandwidthUpgrade(
ClientProxy* client, const std::string& endpoint_id,
const std::vector<proto::connections::Medium>& supported_mediums);
// Returns the optimal medium supported by both devices.
proto::connections::Medium chooseBestUpgradeMedium(
const std::vector<proto::connections::Medium>& their_supported_mediums);
proto::connections::Medium ChooseBestUpgradeMedium(
const std::vector<proto::connections::Medium>& supported_mediums);
// This method should assume ownership of endpoint_id.
void processPreConnectionInitiationFailure(
Ptr<ClientProxy<Platform> > client_proxy,
proto::connections::Medium medium, const string& endpoint_id,
Ptr<EndpointChannel> endpoint_channel, bool is_incoming,
std::int64_t start_time_millis, Status::Value status,
Ptr<SettableFuture<Status::Value> > request_connection_result);
void processPreConnectionResultFailure(
Ptr<ClientProxy<Platform> > client_proxy, const string& endpoint_id);
Ptr<DiscoveredEndpoint> getDiscoveredEndpoint(const string& endpoint_id);
// Returns true if the bluetooth endpoint based on remote bluetooth mac
// address is created and appended into discovered_endpoints_ with key
// endpoint_id.
bool AppendRemoteBluetoothMacAddressEndpoint(
const std::string& endpoint_id,
const std::string& remote_bluetooth_mac_address);
// Returns true if the webrtc endpoint is created and appended into
// discovered_endpoints_ with key endpoint_id.
bool AppendWebRTCEndpoint(const std::string& endpoint_id);
void ProcessPreConnectionInitiationFailure(const std::string& endpoint_id,
EndpointChannel* channel,
Status status,
Future<Status>* result);
void ProcessPreConnectionResultFailure(ClientProxy* client,
const std::string& endpoint_id);
// Called when either side accepts/rejects the connection, but only takes
// effect after both have accepted or one side has rejected.
@@ -435,73 +446,68 @@ class BasePCPHandler
// NOTE: We also take in a 'can_close_immediately' variable. This is because
// any writes in transit are dropped when we close. To avoid having a reject
// write being dropped (which causes the other side to report
// onResult(DISCONNECTED) instead of onResult(REJECTED)), we delay our close.
// If the other side behaves properly, we shouldn't even see the delay
// (because they will also close the connection).
void evaluateConnectionResult(Ptr<ClientProxy<Platform> > client_proxy,
const string& endpoint_id,
// onResult(DISCONNECTED) instead of onResult(REJECTED)), we delay our
// close. If the other side behaves properly, we shouldn't even see the
// delay (because they will also close the connection).
void EvaluateConnectionResult(ClientProxy* client,
const std::string& endpoint_id,
bool can_close_immediately);
ExceptionOr<ConstPtr<OfflineFrame> > readConnectionRequestFrame(
Ptr<EndpointChannel> endpoint_channel);
ExceptionOr<OfflineFrame> ReadConnectionRequestFrame(
EndpointChannel* channel);
void waitForLatch(const string& method_name, Ptr<CountDownLatch> latch);
Status::Value waitForResult(const string& method_name, std::int64_t client_id,
Ptr<Future<Status::Value> > result_future);
void WaitForLatch(const std::string& method_name, CountDownLatch* latch);
Status WaitForResult(const std::string& method_name, std::int64_t client_id,
Future<Status>* future);
ScopedPtr<Ptr<AtomicReference<proto::connections::Medium> > >
bandwidth_upgrade_medium_;
ScopedPtr<Ptr<typename Platform::ScheduledExecutorType> > alarm_executor_;
ScopedPtr<Ptr<typename Platform::SingleThreadExecutorType> > serial_executor_;
ScopedPtr<Ptr<SystemClock> > system_clock_;
Prng prng_;
AtomicReference<Medium> bwu_medium_{Medium::UNKNOWN_MEDIUM};
ScheduledExecutor alarm_executor_;
SingleThreadExecutor serial_executor_;
// A map of endpoint id -> PendingConnectionInfo. Entries in this map imply
// that there is an active connection to the endpoint and we're waiting for
// both sides to accept before allowing payloads through. Once the fate of the
// connection is decided (either accepted or rejected), it should be removed
// from this map.
typedef std::map<string, Ptr<PendingConnectionInfo> > PendingConnectionsMap;
PendingConnectionsMap pending_connections_;
// both sides to accept before allowing payloads through. Once the fate of
// the connection is decided (either accepted or rejected), it should be
// removed from this map.
absl::flat_hash_map<std::string, PendingConnectionInfo> pending_connections_;
// A map of endpoint id -> DiscoveredEndpoint.
typedef std::map<string, Ptr<DiscoveredEndpoint> > DiscoveredEndpointsMap;
DiscoveredEndpointsMap discovered_endpoints_;
absl::btree_multimap<std::string, std::shared_ptr<DiscoveredEndpoint>>
discovered_endpoints_;
// A map of endpoint id -> alarm. These alarms delay closing the
// EndpointChannel to give the other side enough time to read the rejection
// message. It's expected that the other side will close the connection after
// reading the message (in which case, this alarm should be cancelled as it's
// no longer needed), but this alarm is the fallback in case that doesn't
// happen.
typedef std::map<string, Ptr<CancelableAlarm> >
PendingRejectedConnectionCloseAlarmsMap;
PendingRejectedConnectionCloseAlarmsMap
pending_rejected_connection_close_alarms_;
// message. It's expected that the other side will close the connection
// after reading the message (in which case, this alarm should be cancelled
// as it's no longer needed), but this alarm is the fallback in case that
// doesn't happen.
absl::flat_hash_map<std::string, CancelableAlarm> pending_alarms_;
// The active ClientProxy's advertising constraints. Null if the client hasn't
// started advertising. Note: this is not cleared when the client stops
// advertising because it might still be useful downstream of advertising (eg:
// establishing connections, performing bandwidth upgrades, etc.)
Ptr<AdvertisingOptions> advertising_options_;
// The active ClientProxy's advertising constraints. Empty()
// returns true if the client hasn't started advertising false otherwise.
// Note: this is not cleared when the client stops advertising because it
// might still be useful downstream of advertising (eg: establishing
// connections, performing bandwidth upgrades, etc.)
ConnectionOptions advertising_options_;
// The active ClientProxy's connection lifecycle listener. Non-null while
// advertising.
Ptr<ConnectionLifecycleListener> advertising_connection_lifecycle_listener_;
ConnectionListener advertising_listener_;
// The active ClientProxy's discovery constraints. Null if the client
// hasn't started discovering. Note: this is not cleared when the client
// stops discovering because it might still be useful downstream of
// discovery (eg: connection speed, etc.)
Ptr<DiscoveryOptions> discovery_options_;
ConnectionOptions discovery_options_;
// This should have been a ScopedPtr, but we are making this a Ptr to manually
// control the order of destruction.
Ptr<EncryptionRunner<Platform> > encryption_runner_;
std::shared_ptr<BasePCPHandler> self_{this, [](void*){}};
AtomicBoolean stop_{false};
Pcp pcp_;
Strategy strategy_{PcpToStrategy(pcp_)};
Prng prng_;
EncryptionRunner encryption_runner_;
BwuManager* bwu_manager_;
EndpointManager::FrameProcessor::Handle handle_ = nullptr;
};
} // namespace connections
} // namespace nearby
} // namespace location
#include "core/internal/base_pcp_handler.cc"
#endif // CORE_INTERNAL_BASE_PCP_HANDLER_H_