1 //
2 //  Copyright (C) 2015 Google, Inc.
3 //
4 //  Licensed under the Apache License, Version 2.0 (the "License");
5 //  you may not use this file except in compliance with the License.
6 //  You may obtain a copy of the License at:
7 //
8 //  http://www.apache.org/licenses/LICENSE-2.0
9 //
10 //  Unless required by applicable law or agreed to in writing, software
11 //  distributed under the License is distributed on an "AS IS" BASIS,
12 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 //  See the License for the specific language governing permissions and
14 //  limitations under the License.
15 //
16 
17 #pragma once
18 
19 #include <deque>
20 #include <functional>
21 #include <mutex>
22 #include <unordered_map>
23 #include <unordered_set>
24 #include <vector>
25 
26 #include <base/macros.h>
27 
28 #include "service/bluetooth_instance.h"
29 #include "service/common/bluetooth/service.h"
30 #include "service/common/bluetooth/uuid.h"
31 #include "service/hal/bluetooth_gatt_interface.h"
32 
33 namespace bluetooth {
34 
35 // A GattServer instance represents an application's handle to perform GATT
36 // server-role operations. Instances cannot be created directly and should be
37 // obtained through the factory.
38 class GattServer : public BluetoothInstance,
39                    private hal::BluetoothGattInterface::ServerObserver {
40  public:
41   // Delegate interface is used to handle incoming requests and confirmations
42   // for a GATT service.
43   class Delegate {
44    public:
45     Delegate() = default;
46     virtual ~Delegate() = default;
47 
48     // Called when there is an incoming read request for the characteristic with
49     // ID |characteristic_id| from a remote device with address
50     // |device_address|. |request_id| can be used to respond to this request by
51     // calling SendResponse below.
52     virtual void OnCharacteristicReadRequest(GattServer* gatt_server,
53                                              const std::string& device_address,
54                                              int request_id, int offset,
55                                              bool is_long, uint16_t handle) = 0;
56 
57     // Called when there is an incoming read request for the descriptor with
58     // ID |descriptor_id| from a remote device with address |device_address|.
59     // |request_id| can be used to respond to this request by
60     // calling SendResponse below.
61     virtual void OnDescriptorReadRequest(GattServer* gatt_server,
62                                          const std::string& device_address,
63                                          int request_id, int offset,
64                                          bool is_long, uint16_t handle) = 0;
65 
66     // Called when there is an incoming write request for the characteristic
67     // with ID |characteristic_id| from a remote device with address
68     // |device_address|. |request_id| can be used to respond to this request by
69     // calling SendResponse, if the |need_response| parameter is true. Otherwise
70     // this is a "Write Without Reponse" procedure and SendResponse will fail.
71     // If |is_prepare_write| is true, then the write should not be committed
72     // immediately as this is a "Prepared Write Request". Instead, the Delegate
73     // should hold on to the value and either discard it or complete the write
74     // when it receives the OnExecuteWriteRequest event.
75     virtual void OnCharacteristicWriteRequest(
76         GattServer* gatt_server, const std::string& device_address,
77         int request_id, int offset, bool is_prepare_write, bool need_response,
78         const std::vector<uint8_t>& value, uint16_t handle) = 0;
79 
80     // Called when there is an incoming write request for the descriptor
81     // with ID |descriptor_id| from a remote device with address
82     // |device_address|. |request_id| can be used to respond to this request by
83     // calling SendResponse, if the |need_response| parameter is true. Otherwise
84     // this is a "Write Without Response" procedure and SendResponse will fail.
85     // If |is_prepare_write| is true, then the write should not be committed
86     // immediately as this is a "Prepared Write Request". Instead, the Delegate
87     // should hold on to the value and either discard it or complete the write
88     // when it receives the OnExecuteWriteRequest event.
89     virtual void OnDescriptorWriteRequest(
90         GattServer* gatt_server, const std::string& device_address,
91         int request_id, int offset, bool is_prepare_write, bool need_response,
92         const std::vector<uint8_t>& value, uint16_t handle) = 0;
93 
94     // Called when there is an incoming "Execute Write Request". If |is_execute|
95     // is true, then the Delegate should commit all previously prepared writes.
96     // Otherwise, all prepared writes should be aborted. The Delegate should
97     // call "SendResponse" to complete the procedure.
98     virtual void OnExecuteWriteRequest(GattServer* gatt_server,
99                                        const std::string& device_address,
100                                        int request_id, bool is_execute) = 0;
101 
102     virtual void OnConnectionStateChanged(GattServer* gatt_server,
103                                           const std::string& device_addres,
104                                           bool connected) = 0;
105 
106    private:
107     DISALLOW_COPY_AND_ASSIGN(Delegate);
108   };
109 
110   // The desctructor automatically unregisters this instance from the stack.
111   ~GattServer() override;
112 
113   // Assigns a delegate to this instance. |delegate| must out-live this
114   // GattServer instance.
115   void SetDelegate(Delegate* delegate);
116 
117   // BluetoothClientInstace overrides:
118   const UUID& GetAppIdentifier() const override;
119   int GetInstanceId() const override;
120 
121   // Callback type used to report the status of an asynchronous GATT server
122   // operation.
123   using ResultCallback =
124       std::function<void(BLEStatus status, const Service& id)>;
125   using GattCallback = std::function<void(GATTError error)>;
126 
127   // Add service declaration. This method immediately
128   // returns false if a service hasn't been started. Otherwise, |callback| will
129   // be called asynchronously with the result of the operation.
130   //
131   // TODO(armansito): It is unclear to me what it means for this function to
132   // fail. What is the state that we're in? Is the service declaration over so
133   // we can add other services to this server instance? Do we need to clean up
134   // all the entries or does the upper-layer need to remove the service? Or are
135   // we in a stuck-state where the service declaration hasn't ended?
136   bool AddService(const bluetooth::Service&, const ResultCallback& callback);
137 
138   // Sends a response for a pending notification. |request_id| and
139   // |device_address| should match those that were received through one of the
140   // Delegate callbacks. |value| and |offset| are used for read requests and
141   // prepare write requests and should match the value of the attribute. Returns
142   // false if the pending request could not be resolved using the given
143   // parameters or if the call to the underlying stack fails.
144   bool SendResponse(const std::string& device_address, int request_id,
145                     GATTError error, int offset,
146                     const std::vector<uint8_t>& value);
147 
148   // Sends an ATT Handle-Value Notification to the device with BD_ADDR
149   // |device_address| for the characteristic with handle |handle| and
150   // value |value|. If |confirm| is true, then an ATT Handle-Value Indication
151   // will be sent instead, which requires the remote to confirm receipt. Returns
152   // false if there was an immediate error in initiating the notification
153   // procedure. Otherwise, returns true and reports the asynchronous result of
154   // the operation in |callback|.
155   //
156   // If |confirm| is true, then |callback| will be run when the remote device
157   // sends a ATT Handle-Value Confirmation packet. Otherwise, it will be run as
158   // soon as the notification has been sent out.
159   bool SendNotification(const std::string& device_address,
160                         const uint16_t handle, bool confirm,
161                         const std::vector<uint8_t>& value,
162                         const GattCallback& callback);
163 
164  private:
165   friend class GattServerFactory;
166 
167   // Used for the internal remote connection tracking. Keeps track of the
168   // request ID and the device address for the connection. If |request_id| is -1
169   // then no ATT read/write request is currently pending.
170   struct Connection {
ConnectionConnection171     Connection(int conn_id, const bt_bdaddr_t& bdaddr)
172         : conn_id(conn_id), bdaddr(bdaddr) {}
ConnectionConnection173     Connection() : conn_id(-1) { memset(&bdaddr, 0, sizeof(bdaddr)); }
174 
175     int conn_id;
176     std::unordered_map<int, int> request_id_to_handle;
177     bt_bdaddr_t bdaddr;
178   };
179 
180   // Used to keep track of a pending Handle-Value indication.
181   struct PendingIndication {
PendingIndicationPendingIndication182     explicit PendingIndication(const GattCallback& callback)
183         : has_success(false), callback(callback) {}
184 
185     bool has_success;
186     GattCallback callback;
187   };
188 
189   // Constructor shouldn't be called directly as instances are meant to be
190   // obtained from the factory.
191   GattServer(const UUID& uuid, int server_id);
192 
193   // hal::BluetoothGattInterface::ServerObserver overrides:
194   void ConnectionCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id,
195                           int server_id, int connected,
196                           const bt_bdaddr_t& bda) override;
197   void ServiceAddedCallback(hal::BluetoothGattInterface* gatt_iface, int status,
198                             int server_if,
199                             std::vector<btgatt_db_element_t>) override;
200   void ServiceStoppedCallback(hal::BluetoothGattInterface* gatt_iface,
201                               int status, int server_id,
202                               int service_handle) override;
203   void RequestReadCharacteristicCallback(
204       hal::BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
205       const bt_bdaddr_t& bda, int attribute_handle, int offset,
206       bool is_long) override;
207   void RequestReadDescriptorCallback(hal::BluetoothGattInterface* gatt_iface,
208                                      int conn_id, int trans_id,
209                                      const bt_bdaddr_t& bda,
210                                      int attribute_handle, int offset,
211                                      bool is_long) override;
212   void RequestWriteCharacteristicCallback(
213       hal::BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
214       const bt_bdaddr_t& bda, int attr_handle, int offset, bool need_rsp,
215       bool is_prep, std::vector<uint8_t> value) override;
216   void RequestWriteDescriptorCallback(hal::BluetoothGattInterface* gatt_iface,
217                                       int conn_id, int trans_id,
218                                       const bt_bdaddr_t& bda, int attr_handle,
219                                       int offset, bool need_rsp, bool is_prep,
220                                       std::vector<uint8_t> value) override;
221   void RequestExecWriteCallback(hal::BluetoothGattInterface* gatt_iface,
222                                 int conn_id, int trans_id,
223                                 const bt_bdaddr_t& bda,
224                                 int exec_write) override;
225   void IndicationSentCallback(hal::BluetoothGattInterface* gatt_iface,
226                               int conn_id, int status) override;
227 
228   // Helper function that notifies and clears the pending callback.
229   void CleanUpPendingData();
230 
231   // Handles the next attribute entry in the pending service declaration.
232   void HandleNextEntry(hal::BluetoothGattInterface* gatt_iface);
233 
234   // Helper method that returns a pointer to an internal Connection instance
235   // that matches the given parameters.
236   std::shared_ptr<Connection> GetConnection(int conn_id, const bt_bdaddr_t& bda,
237                                             int request_id);
238 
239   // See getters for documentation.
240   UUID app_identifier_;
241   int server_id_;
242 
243   // Mutex that synchronizes access to the entries below.
244   std::mutex mutex_;
245   ResultCallback pending_end_decl_cb_;
246 
247   // GATT connection mappings from stack-provided "conn_id" IDs and remote
248   // device addresses to Connection structures. The conn_id map is one-to-one
249   // while the conn_addr map is one to many, as a remote device may support
250   // multiple transports (BR/EDR & LE) and use the same device address for both.
251   std::unordered_map<int, std::shared_ptr<Connection>> conn_id_map_;
252   std::unordered_map<std::string, std::vector<std::shared_ptr<Connection>>>
253       conn_addr_map_;
254 
255   // Connections for which a Handle-Value indication is pending. Since there can
256   // be multiple indications to the same device (in the case of a dual-mode
257   // device with simulatenous BR/EDR & LE GATT connections), we also keep track
258   // of whether there has been at least one successful confirmation.
259   std::unordered_map<int, std::shared_ptr<PendingIndication>>
260       pending_indications_;
261 
262   // Raw handle to the Delegate, which must outlive this GattServer instance.
263   Delegate* delegate_;
264 
265   DISALLOW_COPY_AND_ASSIGN(GattServer);
266 };
267 
268 // GattServerFactory is used to register and obtain a per-application GattServer
269 // instance. Users should call RegisterClient to obtain their own unique
270 // GattServer instance that has been registered with the Bluetooth stack.
271 class GattServerFactory : public BluetoothInstanceFactory,
272                           private hal::BluetoothGattInterface::ServerObserver {
273  public:
274   // Don't construct/destruct directly except in tests. Instead, obtain a handle
275   // from an Adapter instance.
276   GattServerFactory();
277   ~GattServerFactory() override;
278 
279   // BluetoothInstanceFactory override:
280   bool RegisterInstance(const UUID& uuid,
281                         const RegisterCallback& callback) override;
282 
283  private:
284   // hal::BluetoothGattInterface::ServerObserver override:
285   void RegisterServerCallback(hal::BluetoothGattInterface* gatt_iface,
286                               int status, int server_id,
287                               const bt_uuid_t& app_uuid) override;
288 
289   // Map of pending calls to register.
290   std::mutex pending_calls_lock_;
291   std::unordered_map<UUID, RegisterCallback> pending_calls_;
292 
293   DISALLOW_COPY_AND_ASSIGN(GattServerFactory);
294 };
295 
296 }  // namespace bluetooth
297