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