• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #pragma once
16 #include <lib/fit/function.h>
17 
18 #include <list>
19 #include <memory>
20 #include <unordered_map>
21 #include <unordered_set>
22 #include <vector>
23 
24 #include "lib/fit/result.h"
25 #include "pw_bluetooth_sapphire/internal/host/common/error.h"
26 #include "pw_bluetooth_sapphire/internal/host/common/macros.h"
27 #include "pw_bluetooth_sapphire/internal/host/common/metrics.h"
28 #include "pw_bluetooth_sapphire/internal/host/common/windowed_inspect_numeric_property.h"
29 #include "pw_bluetooth_sapphire/internal/host/gap/adapter_state.h"
30 #include "pw_bluetooth_sapphire/internal/host/gap/gap.h"
31 #include "pw_bluetooth_sapphire/internal/host/gap/low_energy_connection_request.h"
32 #include "pw_bluetooth_sapphire/internal/host/gap/low_energy_connector.h"
33 #include "pw_bluetooth_sapphire/internal/host/gap/low_energy_discovery_manager.h"
34 #include "pw_bluetooth_sapphire/internal/host/gatt/gatt.h"
35 #include "pw_bluetooth_sapphire/internal/host/hci/low_energy_connection.h"
36 #include "pw_bluetooth_sapphire/internal/host/hci/low_energy_connector.h"
37 #include "pw_bluetooth_sapphire/internal/host/l2cap/channel_manager.h"
38 #include "pw_bluetooth_sapphire/internal/host/sm/error.h"
39 #include "pw_bluetooth_sapphire/internal/host/sm/security_manager.h"
40 #include "pw_bluetooth_sapphire/internal/host/sm/types.h"
41 #include "pw_bluetooth_sapphire/internal/host/transport/command_channel.h"
42 #include "pw_bluetooth_sapphire/internal/host/transport/control_packets.h"
43 #include "pw_bluetooth_sapphire/internal/host/transport/error.h"
44 #include "pw_bluetooth_sapphire/internal/host/transport/transport.h"
45 
46 namespace bt {
47 
48 namespace hci {
49 class LocalAddressDelegate;
50 }  // namespace hci
51 
52 namespace gap {
53 
54 namespace internal {
55 class LowEnergyConnection;
56 }  // namespace internal
57 
58 // TODO(armansito): Document the usage pattern.
59 
60 class LowEnergyConnectionManager;
61 class PairingDelegate;
62 class Peer;
63 class PeerCache;
64 
65 enum class LowEnergyDisconnectReason : uint8_t {
66   // Explicit disconnect request
67   kApiRequest,
68   // An internal error was encountered
69   kError,
70 };
71 
72 // LowEnergyConnectionManager is responsible for connecting and initializing new
73 // connections, interrogating connections, intiating pairing, and disconnecting
74 // connections.
75 class LowEnergyConnectionManager final {
76  public:
77   // Duration after which connection failures are removed from Inspect.
78   static constexpr pw::chrono::SystemClock::duration
79       kInspectRecentConnectionFailuresExpiryDuration = std::chrono::minutes(10);
80 
81   // |hci|: The HCI transport used to track link layer connection events from
82   //        the controller.
83   // |addr_delegate|: Used to obtain local identity information during pairing
84   //                  procedures.
85   // |connector|: Adapter object for initiating link layer connections. This
86   //              object abstracts the legacy and extended HCI command sets.
87   // |peer_cache|: The cache that stores peer peer data. The connection
88   //                 manager stores and retrieves pairing data and connection
89   //                 parameters to/from the cache. It also updates the
90   //                 connection and bonding state of a peer via the cache.
91   // |l2cap|: Used to interact with the L2CAP layer.
92   // |gatt|: Used to interact with the GATT profile layer.
93   // |adapter_state|: Provides information on controller capabilities.
94   LowEnergyConnectionManager(
95       hci::Transport::WeakPtr hci,
96       hci::LocalAddressDelegate* addr_delegate,
97       hci::LowEnergyConnector* connector,
98       PeerCache* peer_cache,
99       l2cap::ChannelManager* l2cap,
100       gatt::GATT::WeakPtr gatt,
101       LowEnergyDiscoveryManager::WeakPtr discovery_manager,
102       sm::SecurityManagerFactory sm_creator,
103       const AdapterState& adapter_state,
104       pw::async::Dispatcher& dispatcher);
105   ~LowEnergyConnectionManager();
106 
107   // Allows a caller to claim shared ownership over a connection to the
108   // requested remote LE peer identified by |peer_id|.
109   //   * If |peer_id| is not recognized, |callback| is called with an error.
110   //
111   //   * If the requested peer is already connected, |callback| is called with a
112   //     LowEnergyConnectionHandle immediately.
113   //     This is done for both local and remote initiated connections (i.e. the
114   //     local adapter can either be in the LE central or peripheral roles).
115   //
116   //   * If the requested peer is NOT connected, then this method initiates a
117   //     connection to the requested peer using the
118   //     internal::LowEnergyConnector. See that class's documentation for a more
119   //     detailed overview of the Connection process. A
120   //     LowEnergyConnectionHandle is asynchronously returned to the caller once
121   //     the connection has been set up.
122   //
123   // The status of the procedure is reported in |callback| in the case of an
124   // error.
125   using ConnectionResult =
126       fit::result<HostError, std::unique_ptr<LowEnergyConnectionHandle>>;
127   using ConnectionResultCallback = fit::function<void(ConnectionResult)>;
128   void Connect(PeerId peer_id,
129                ConnectionResultCallback callback,
130                LowEnergyConnectionOptions connection_options);
131 
local_address_delegate()132   hci::LocalAddressDelegate* local_address_delegate() const {
133     return local_address_delegate_;
134   }
135 
136   // Disconnects any existing or pending LE connection to |peer_id|,
137   // invalidating all active LowEnergyConnectionHandles. Returns false if the
138   // peer can not be disconnected.
139   bool Disconnect(PeerId peer_id,
140                   LowEnergyDisconnectReason reason =
141                       LowEnergyDisconnectReason::kApiRequest);
142 
143   // Initializes a new connection over the given |link| and asynchronously
144   // returns a connection reference.
145   //
146   // |link| must be the result of a remote initiated connection.
147   //
148   // |callback| will be called with a connection status and connection
149   // reference. The connection reference will be nullptr if the connection was
150   // rejected (as indicated by a failure status).
151   //
152   // TODO(armansito): Add an |own_address| parameter for the locally advertised
153   // address that was connected to.
154   //
155   // A link with the given handle should not have been previously registered.
156   void RegisterRemoteInitiatedLink(
157       std::unique_ptr<hci::LowEnergyConnection> link,
158       sm::BondableMode bondable_mode,
159       ConnectionResultCallback callback);
160 
161   // Returns the PairingDelegate currently assigned to this connection manager.
pairing_delegate()162   const PairingDelegate::WeakPtr& pairing_delegate() const {
163     return pairing_delegate_;
164   }
165 
166   // Assigns a new PairingDelegate to handle LE authentication challenges.
167   // Replacing an existing pairing delegate cancels all ongoing pairing
168   // procedures. If a delegate is not set then all pairing requests will be
169   // rejected.
170   void SetPairingDelegate(const PairingDelegate::WeakPtr& delegate);
171 
172   // Opens a new L2CAP channel to service |psm| on |peer_id| using the preferred
173   // parameters |params|.
174   //
175   // |cb| will be called with the channel created to the peer, or nullptr if the
176   // channel creation resulted in an error.
177   void OpenL2capChannel(PeerId peer_id,
178                         l2cap::Psm psm,
179                         l2cap::ChannelParameters params,
180                         sm::SecurityLevel security_level,
181                         l2cap::ChannelCallback cb);
182 
183   // TODO(armansito): Add a PeerCache::Observer interface and move these
184   // callbacks there.
185 
186   // Called when a link with the given handle gets disconnected. This event is
187   // guaranteed to be called before invalidating connection references.
188   // |callback| is run on the creation thread.
189   //
190   // NOTE: This is intended ONLY for unit tests. Clients should watch for
191   // disconnection events using LowEnergyConnectionHandle::set_closed_callback()
192   // instead. DO NOT use outside of tests.
193   using DisconnectCallback = fit::function<void(hci_spec::ConnectionHandle)>;
194   void SetDisconnectCallbackForTesting(DisconnectCallback callback);
195 
196   // Sets the timeout interval to be used on future connect requests. The
197   // default value is kLECreateConnectionTimeout.
set_request_timeout_for_testing(pw::chrono::SystemClock::duration value)198   void set_request_timeout_for_testing(
199       pw::chrono::SystemClock::duration value) {
200     request_timeout_ = value;
201   }
202 
203   // Callback for hci::Connection, called when the peer disconnects.
204   // |reason| is used to control retry logic.
205   void OnPeerDisconnect(const hci::Connection* connection,
206                         pw::bluetooth::emboss::StatusCode reason);
207 
208   // Initiates the pairing process. Expected to only be called during
209   // higher-level testing.
210   //   |peer_id|: the peer to pair to - if the peer is not connected, |cb| is
211   //   called with an error. |pairing_level|: determines the security level of
212   //   the pairing. **Note**: If the security
213   //                    level of the link is already >= |pairing level|, no
214   //                    pairing takes place.
215   //   |bondable_mode|: sets the bonding mode of this connection. A device in
216   //   bondable mode forms a
217   //                    bond to the peer upon pairing, assuming the peer is also
218   //                    in bondable mode. A device in non-bondable mode will not
219   //                    allow pairing that forms a bond.
220   //   |cb|: callback called upon completion of this function, whether pairing
221   //   takes place or not.
222   void Pair(PeerId peer_id,
223             sm::SecurityLevel pairing_level,
224             sm::BondableMode bondable_mode,
225             sm::ResultFunction<> cb);
226 
227   // Sets the LE security mode of the local device (see v5.2 Vol. 3 Part C
228   // Section 10.2). If set to SecureConnectionsOnly, any currently encrypted
229   // links not meeting the requirements of Security Mode 1 Level 4 will be
230   // disconnected.
231   void SetSecurityMode(LESecurityMode mode);
232 
233   // Attach manager inspect node as a child node of |parent|.
234   void AttachInspect(inspect::Node& parent, std::string name);
235 
security_mode()236   LESecurityMode security_mode() const { return security_mode_; }
sm_factory_func()237   sm::SecurityManagerFactory sm_factory_func() const {
238     return sm_factory_func_;
239   }
240 
241   using WeakPtr = WeakSelf<LowEnergyConnectionManager>::WeakPtr;
242 
243  private:
244   friend class internal::LowEnergyConnection;
245 
246   // Mapping from peer identifiers to open LE connections.
247   using ConnectionMap =
248       std::unordered_map<PeerId,
249                          std::unique_ptr<internal::LowEnergyConnection>>;
250 
251   // Called by LowEnergyConnectionHandle::Release().
252   void ReleaseReference(LowEnergyConnectionHandle* handle);
253 
254   // Initiates a new connection attempt for the next peer in the pending list,
255   // if any.
256   void TryCreateNextConnection();
257 
258   // Called by internal::LowEnergyConnector to indicate the result of a local
259   // connect request.
260   void OnLocalInitiatedConnectResult(
261       hci::Result<std::unique_ptr<internal::LowEnergyConnection>> result);
262 
263   // Called by internal::LowEnergyConnector to indicate the result of a remote
264   // connect request.
265   void OnRemoteInitiatedConnectResult(
266       PeerId peer_id,
267       hci::Result<std::unique_ptr<internal::LowEnergyConnection>> result);
268 
269   // Either report an error to clients or initialize the connection and report
270   // success to clients.
271   void ProcessConnectResult(
272       hci::Result<std::unique_ptr<internal::LowEnergyConnection>> result,
273       internal::LowEnergyConnectionRequest request);
274 
275   // Finish setting up connection, adding to |connections_| map, and notifying
276   // clients.
277   bool InitializeConnection(
278       std::unique_ptr<internal::LowEnergyConnection> connection,
279       internal::LowEnergyConnectionRequest request);
280 
281   // Cleans up a connection state. This results in a HCI_Disconnect command if
282   // the connection has not already been disconnected, and notifies any
283   // referenced LowEnergyConnectionHandles of the disconnection. Marks the
284   // corresponding PeerCache entry as disconnected and cleans up all data
285   // bearers.
286   //
287   // |conn_state| will have been removed from the underlying map at the time of
288   // a call. Its ownership is passed to the method for disposal.
289   //
290   // This is also responsible for unregistering the link from managed subsystems
291   // (e.g. L2CAP).
292   void CleanUpConnection(std::unique_ptr<internal::LowEnergyConnection> conn);
293 
294   // Updates |peer_cache_| with the given |link| and returns the corresponding
295   // Peer.
296   //
297   // Creates a new Peer if |link| matches a peer that did not
298   // previously exist in the cache. Otherwise this updates and returns an
299   // existing Peer.
300   //
301   // The returned peer is marked as non-temporary and its connection
302   // parameters are updated.
303   //
304   // Called by RegisterRemoteInitiatedLink() and RegisterLocalInitiatedLink().
305   Peer* UpdatePeerWithLink(const hci::LowEnergyConnection& link);
306 
307   // Called when the peer disconnects with a "Connection Failed to be
308   // Established" error. Cleans up the existing connection and adds the
309   // connection request back to the queue for a retry.
310   void CleanUpAndRetryConnection(
311       std::unique_ptr<internal::LowEnergyConnection> connection);
312 
313   // Returns an iterator into |connections_| if a connection is found that
314   // matches the given logical link |handle|. Otherwise, returns an iterator
315   // that is equal to |connections_.end()|.
316   //
317   // The general rules of validity around std::unordered_map::iterator apply to
318   // the returned value.
319   ConnectionMap::iterator FindConnection(hci_spec::ConnectionHandle handle);
320 
321   pw::async::Dispatcher& dispatcher_;
322 
323   hci::Transport::WeakPtr hci_;
324 
325   // The pairing delegate used for authentication challenges. If nullptr, all
326   // pairing requests will be rejected.
327   PairingDelegate::WeakPtr pairing_delegate_;
328 
329   // The GAP LE security mode of the device (v5.2 Vol. 3 Part C 10.2).
330   LESecurityMode security_mode_;
331 
332   // The function used to create each channel's SecurityManager implementation.
333   sm::SecurityManagerFactory sm_factory_func_;
334 
335   // Time after which a connection attempt is considered to have timed out. This
336   // is configurable to allow unit tests to set a shorter value.
337   pw::chrono::SystemClock::duration request_timeout_;
338 
339   // The peer cache is used to look up and persist remote peer data that is
340   // relevant during connection establishment (such as the address, preferred
341   // connection parameters, etc). Expected to outlive this instance.
342   PeerCache* peer_cache_;  // weak
343 
344   // The reference to L2CAP, used to interact with the L2CAP layer to
345   // manage LE logical links, fixed channels, and LE-specific L2CAP signaling
346   // events (e.g. connection parameter update).
347   l2cap::ChannelManager* l2cap_;
348 
349   // The GATT layer reference, used to add and remove ATT data bearers and
350   // service discovery.
351   gatt::GATT::WeakPtr gatt_;
352 
353   // Provides us with information on the capabilities of our controller
354   AdapterState adapter_state_;
355 
356   // Local GATT service registry.
357   std::unique_ptr<gatt::LocalServiceManager> gatt_registry_;
358 
359   LowEnergyDiscoveryManager::WeakPtr discovery_manager_;
360 
361   // Callbacks used by unit tests to observe connection state events.
362   DisconnectCallback test_disconn_cb_;
363 
364   // Outstanding connection requests based on remote peer ID.
365   std::unordered_map<PeerId, internal::LowEnergyConnectionRequest>
366       pending_requests_;
367 
368   // Mapping from peer identifiers to currently open LE connections.
369   ConnectionMap connections_;
370 
371   struct RequestAndConnector {
372     internal::LowEnergyConnectionRequest request;
373     std::unique_ptr<internal::LowEnergyConnector> connector;
374   };
375   // The in-progress locally initiated connection request, if any.
376   std::optional<RequestAndConnector> current_request_;
377 
378   // Active connectors for remote connection requests.
379   std::unordered_map<PeerId, RequestAndConnector> remote_connectors_;
380 
381   // For passing to internal::LowEnergyConnector. |hci_connector_| must
382   // out-live this connection manager.
383   hci::LowEnergyConnector* hci_connector_;  // weak
384 
385   // Address manager is used to obtain local identity information during pairing
386   // procedures. Expected to outlive this instance.
387   hci::LocalAddressDelegate* local_address_delegate_;  // weak
388 
389   // True if the connection manager is performing a scan for a peer before
390   // connecting.
391   bool scanning_ = false;
392 
393   struct InspectProperties {
394     // Count of connection failures in the past 10 minutes.
InspectPropertiesInspectProperties395     explicit InspectProperties(pw::async::Dispatcher& pw_dispatcher)
396         : recent_connection_failures(
397               pw_dispatcher, kInspectRecentConnectionFailuresExpiryDuration) {}
398     WindowedInspectIntProperty recent_connection_failures;
399 
400     UintMetricCounter outgoing_connection_success_count_;
401     UintMetricCounter outgoing_connection_failure_count_;
402     UintMetricCounter incoming_connection_success_count_;
403     UintMetricCounter incoming_connection_failure_count_;
404 
405     UintMetricCounter disconnect_explicit_disconnect_count_;
406     UintMetricCounter disconnect_link_error_count_;
407     UintMetricCounter disconnect_zero_ref_count_;
408     UintMetricCounter disconnect_remote_disconnection_count_;
409   };
410   InspectProperties inspect_properties_{dispatcher_};
411   inspect::Node inspect_node_;
412   // Container node for pending request nodes.
413   inspect::Node inspect_pending_requests_node_;
414   // container node for connection nodes.
415   inspect::Node inspect_connections_node_;
416 
417   // Keep this as the last member to make sure that all weak pointers are
418   // invalidated before other members get destroyed.
419   WeakSelf<LowEnergyConnectionManager> weak_self_;
420 
421   BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(LowEnergyConnectionManager);
422 };
423 
424 }  // namespace gap
425 }  // namespace bt
426