1 //
2 //  Copyright 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 #include "service/adapter.h"
18 
19 #include <atomic>
20 #include <mutex>
21 #include <string>
22 #include <unordered_set>
23 
24 #include <base/logging.h>
25 #include <base/observer_list.h>
26 
27 #include "abstract_observer_list.h"
28 #include "service/a2dp_sink.h"
29 #include "service/a2dp_source.h"
30 #include "service/avrcp_control.h"
31 #include "service/avrcp_target.h"
32 #include "service/common/bluetooth/util/atomic_string.h"
33 #include "service/gatt_client.h"
34 #include "service/gatt_server.h"
35 #include "service/hal/bluetooth_interface.h"
36 #include "service/logging_helpers.h"
37 #include "service/low_energy_advertiser.h"
38 #include "service/low_energy_client.h"
39 #include "service/low_energy_scanner.h"
40 
41 using std::lock_guard;
42 using std::mutex;
43 
44 namespace bluetooth {
45 
46 namespace {
47 
ParseRemoteDeviceProps(int num_properties,bt_property_t * properties)48 RemoteDeviceProps ParseRemoteDeviceProps(int num_properties,
49                                          bt_property_t* properties) {
50   std::string name;
51   std::string address;
52   std::vector<Uuid> service_uuids;
53   int32_t device_class = 0;
54   int32_t device_type = 0;
55   int32_t rssi = 0;
56 
57   for (int i = 0; i < num_properties; ++i) {
58     bt_property_t* property = properties + i;
59     switch (property->type) {
60       case BT_PROPERTY_BDNAME: {
61         if (property->len < 0) {
62           NOTREACHED() << "Invalid length for BT_PROPERTY_BDNAME";
63           break;
64         }
65         bt_bdname_t* hal_name = reinterpret_cast<bt_bdname_t*>(property->val);
66         name = reinterpret_cast<char*>(hal_name->name);
67         break;
68       }
69       case BT_PROPERTY_BDADDR: {
70         if (property->len != sizeof(RawAddress)) {
71           NOTREACHED() << "Invalid length for BT_PROPERTY_BDADDR";
72           break;
73         }
74         address = BtAddrString(reinterpret_cast<RawAddress*>(property->val));
75         break;
76       }
77       case BT_PROPERTY_UUIDS: {
78         if (property->len < 0) {
79           NOTREACHED() << "Negative length on BT_PROPERTY_UUIDS:";
80           break;
81         }
82         if (property->len % sizeof(Uuid) != 0) {
83           NOTREACHED() << "Trailing bytes on BT_PROPERTY_UUIDS:";
84         }
85         auto uuids = static_cast<const Uuid*>(property->val);
86 
87         for (size_t i = 0; i < property->len / sizeof(Uuid); ++i) {
88           service_uuids.push_back(uuids[i]);
89         }
90         break;
91       }
92       case BT_PROPERTY_CLASS_OF_DEVICE: {
93         if (property->len != sizeof(int32_t)) {
94           NOTREACHED() << "Invalid length for BT_PROPERTY_CLASS_OF_DEVICE";
95           break;
96         }
97         device_class = *reinterpret_cast<const int32_t*>(property->val);
98         break;
99       }
100       case BT_PROPERTY_TYPE_OF_DEVICE: {
101         if (property->len != sizeof(int32_t)) {
102           NOTREACHED() << "Invalid length for BT_PROPERTY_TYPE_OF_DEVICE";
103           break;
104         }
105         device_type = *reinterpret_cast<const int32_t*>(property->val);
106         break;
107       }
108       case BT_PROPERTY_REMOTE_RSSI: {
109         if (property->len != sizeof(int8_t)) {
110           NOTREACHED() << "Invalid length for BT_PROPERTY_REMOTE_RSSI";
111           break;
112         }
113         rssi = *reinterpret_cast<const int8_t*>(property->val);
114         break;
115       }
116       default:
117         VLOG(1) << "Unhandled adapter property: "
118                 << BtPropertyText(property->type);
119         break;
120     }
121   }
122 
123   return RemoteDeviceProps(name, address, service_uuids, device_class,
124                            device_type, rssi);
125 }
126 
127 }  // namespace
128 
129 // static
130 const char Adapter::kDefaultAddress[] = "00:00:00:00:00:00";
131 // static
132 const char Adapter::kDefaultName[] = "not-initialized";
133 
134 // TODO(armansito): The following constants come straight from
135 // packages/apps/Bluetooth/src/c/a/b/btservice/AdapterService.java. It would be
136 // nice to know if there were a way to obtain these values from the stack
137 // instead of hardcoding them here.
138 
139 // The minimum number of advertising instances required for multi-advertisement
140 // support.
141 const int kMinAdvInstancesForMultiAdv = 5;
142 
143 // Used when determining if offloaded scan filtering is supported.
144 const int kMinOffloadedFilters = 10;
145 
146 // Used when determining if offloaded scan batching is supported.
147 const int kMinOffloadedScanStorageBytes = 1024;
148 
OnAdapterStateChanged(Adapter * adapter,AdapterState prev_state,AdapterState new_state)149 void Adapter::Observer::OnAdapterStateChanged(Adapter* adapter,
150                                               AdapterState prev_state,
151                                               AdapterState new_state) {
152   // Default implementation does nothing
153 }
154 
OnDeviceConnectionStateChanged(Adapter * adapter,const std::string & device_address,bool connected)155 void Adapter::Observer::OnDeviceConnectionStateChanged(
156     Adapter* adapter, const std::string& device_address, bool connected) {
157   // Default implementation does nothing
158 }
159 
OnScanEnableChanged(Adapter * adapter,bool scan_enabled)160 void Adapter::Observer::OnScanEnableChanged(Adapter* adapter,
161                                             bool scan_enabled) {
162   // Default implementation does nothing
163 }
164 
OnSspRequest(Adapter * adapter,const std::string & device_address,const std::string & device_name,int cod,int pairing_variant,int pass_key)165 void Adapter::Observer::OnSspRequest(Adapter* adapter,
166                                      const std::string& device_address,
167                                      const std::string& device_name, int cod,
168                                      int pairing_variant, int pass_key) {
169   // Default implementation does nothing
170 }
171 
OnBondStateChanged(Adapter * adapter,int status,const std::string & device_address,int state)172 void Adapter::Observer::OnBondStateChanged(Adapter* adapter, int status,
173                                            const std::string& device_address,
174                                            int state) {
175   // Default implementation does nothing
176 }
177 
OnGetBondedDevices(Adapter * adapter,int status,const std::vector<std::string> & bonded_devices)178 void Adapter::Observer::OnGetBondedDevices(
179     Adapter* adapter, int status,
180     const std::vector<std::string>& bonded_devices) {
181   // Default implementation does nothing
182 }
183 
OnGetRemoteDeviceProperties(Adapter * adapter,int status,const std::string & device_address,const RemoteDeviceProps & properties)184 void Adapter::Observer::OnGetRemoteDeviceProperties(
185     Adapter* adapter, int status, const std::string& device_address,
186     const RemoteDeviceProps& properties) {
187   // Default implementation does nothing
188 }
189 
OnDeviceFound(Adapter * adapter,const RemoteDeviceProps & properties)190 void Adapter::Observer::OnDeviceFound(Adapter* adapter,
191                                       const RemoteDeviceProps& properties) {
192   // Default implementation does nothing
193 }
194 
195 // The real Adapter implementation used in production.
196 class AdapterImpl : public Adapter, public hal::BluetoothInterface::Observer {
197  public:
AdapterImpl()198   AdapterImpl()
199       : state_(ADAPTER_STATE_OFF),
200         address_(kDefaultAddress),
201         name_(kDefaultName) {
202     memset(&local_le_features_, 0, sizeof(local_le_features_));
203     hal::BluetoothInterface::Get()->AddObserver(this);
204     a2dp_sink_factory_.reset(new A2dpSinkFactory);
205     a2dp_source_factory_.reset(new A2dpSourceFactory);
206     avrcp_control_factory_.reset(new AvrcpControlFactory);
207     avrcp_target_factory_.reset(new AvrcpTargetFactory);
208     ble_client_factory_.reset(new LowEnergyClientFactory(*this));
209     ble_advertiser_factory_.reset(new LowEnergyAdvertiserFactory());
210     ble_scanner_factory_.reset(new LowEnergyScannerFactory(*this));
211     gatt_client_factory_.reset(new GattClientFactory());
212     gatt_server_factory_.reset(new GattServerFactory());
213     hal::BluetoothInterface::Get()->GetHALInterface()->get_adapter_properties();
214   }
215 
~AdapterImpl()216   ~AdapterImpl() override {
217     hal::BluetoothInterface::Get()->RemoveObserver(this);
218   }
219 
AddObserver(Adapter::Observer * observer)220   void AddObserver(Adapter::Observer* observer) override {
221     lock_guard<mutex> lock(observers_lock_);
222     observers_.AddObserver(observer);
223   }
224 
RemoveObserver(Adapter::Observer * observer)225   void RemoveObserver(Adapter::Observer* observer) override {
226     lock_guard<mutex> lock(observers_lock_);
227     observers_.RemoveObserver(observer);
228   }
229 
GetState() const230   AdapterState GetState() const override { return state_.load(); }
231 
IsEnabled() const232   bool IsEnabled() const override { return state_.load() == ADAPTER_STATE_ON; }
233 
Enable()234   bool Enable() override {
235     AdapterState current_state = GetState();
236     if (current_state != ADAPTER_STATE_OFF) {
237       LOG(INFO) << "Adapter not disabled - state: "
238                 << AdapterStateToString(current_state);
239       return false;
240     }
241 
242     // Set the state before calling enable() as there might be a race between
243     // here and the AdapterStateChangedCallback.
244     state_ = ADAPTER_STATE_TURNING_ON;
245     NotifyAdapterStateChanged(current_state, state_);
246 
247     int status = hal::BluetoothInterface::Get()->GetHALInterface()->enable();
248     if (status != BT_STATUS_SUCCESS) {
249       LOG(ERROR) << "Failed to enable Bluetooth - status: "
250                  << BtStatusText((const bt_status_t)status);
251       state_ = ADAPTER_STATE_OFF;
252       NotifyAdapterStateChanged(ADAPTER_STATE_TURNING_ON, state_);
253       return false;
254     }
255 
256     return true;
257   }
258 
Disable()259   bool Disable() override {
260     if (!IsEnabled()) {
261       LOG(INFO) << "Adapter is not enabled";
262       return false;
263     }
264 
265     AdapterState current_state = GetState();
266 
267     // Set the state before calling enable() as there might be a race between
268     // here and the AdapterStateChangedCallback.
269     state_ = ADAPTER_STATE_TURNING_OFF;
270     NotifyAdapterStateChanged(current_state, state_);
271 
272     int status = hal::BluetoothInterface::Get()->GetHALInterface()->disable();
273     if (status != BT_STATUS_SUCCESS) {
274       LOG(ERROR) << "Failed to disable Bluetooth - status: "
275                  << BtStatusText((const bt_status_t)status);
276       state_ = current_state;
277       NotifyAdapterStateChanged(ADAPTER_STATE_TURNING_OFF, state_);
278       return false;
279     }
280 
281     return true;
282   }
283 
GetName() const284   std::string GetName() const override { return name_.Get(); }
285 
SetName(const std::string & name)286   bool SetName(const std::string& name) override {
287     bt_bdname_t hal_name;
288     size_t max_name_len = sizeof(hal_name.name);
289 
290     // Include the \0 byte in size measurement.
291     if (name.length() >= max_name_len) {
292       LOG(ERROR) << "Given name \"" << name << "\" is larger than maximum"
293                  << " allowed size: " << max_name_len;
294       return false;
295     }
296 
297     strncpy(reinterpret_cast<char*>(hal_name.name), name.c_str(),
298             name.length() + 1);
299 
300     VLOG(1) << "Setting adapter name: " << name;
301 
302     if (!SetAdapterProperty(BT_PROPERTY_BDNAME, &hal_name, sizeof(hal_name))) {
303       LOG(ERROR) << "Failed to set adapter name: " << name;
304       return false;
305     }
306 
307     return true;
308   }
309 
GetAddress() const310   std::string GetAddress() const override { return address_.Get(); }
311 
SetScanMode(int scan_mode)312   bool SetScanMode(int scan_mode) override {
313     switch (scan_mode) {
314       case BT_SCAN_MODE_NONE:
315       case BT_SCAN_MODE_CONNECTABLE:
316       case BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE:
317         break;
318       default:
319         LOG(ERROR) << "Unknown scan mode: " << scan_mode;
320         return false;
321     }
322 
323     auto bd_scanmode = static_cast<bt_scan_mode_t>(scan_mode);
324 
325     if (!SetAdapterProperty(BT_PROPERTY_ADAPTER_SCAN_MODE, &bd_scanmode,
326                             sizeof(bd_scanmode))) {
327       LOG(ERROR) << "Failed to set scan mode to : " << scan_mode;
328       return false;
329     }
330 
331     return true;
332   }
333 
SetScanEnable(bool scan_enable)334   bool SetScanEnable(bool scan_enable) override {
335     if (scan_enable) {
336       int status =
337           hal::BluetoothInterface::Get()->GetHALInterface()->start_discovery();
338       if (status != BT_STATUS_SUCCESS) {
339         LOG(ERROR) << "Failed to enable scanning";
340         return false;
341       }
342     } else {
343       int status =
344           hal::BluetoothInterface::Get()->GetHALInterface()->cancel_discovery();
345       if (status != BT_STATUS_SUCCESS) {
346         LOG(ERROR) << "Failed to disable scanning";
347         return false;
348       }
349     }
350     return true;
351   }
352 
SspReply(const std::string & device_address,int variant,bool accept,int32_t pass_key)353   bool SspReply(const std::string& device_address, int variant, bool accept,
354                 int32_t pass_key) override {
355     RawAddress addr;
356     if (!RawAddress::FromString(device_address, addr)) {
357       LOG(ERROR) << "Invalid device address given: " << device_address;
358       return false;
359     }
360 
361     int status = hal::BluetoothInterface::Get()->GetHALInterface()->ssp_reply(
362         &addr, static_cast<bt_ssp_variant_t>(variant), accept, pass_key);
363     if (status != BT_STATUS_SUCCESS) {
364       LOG(ERROR) << "Failed to send SSP response - status: "
365                  << BtStatusText((const bt_status_t)status);
366       return false;
367     }
368 
369     return true;
370   }
371 
CreateBond(const std::string & device_address,int transport)372   bool CreateBond(const std::string& device_address, int transport) override {
373     RawAddress addr;
374     if (!RawAddress::FromString(device_address, addr)) {
375       LOG(ERROR) << "Invalid device address given: " << device_address;
376       return false;
377     }
378 
379     int status = hal::BluetoothInterface::Get()->GetHALInterface()->create_bond(
380         &addr, transport);
381     if (status != BT_STATUS_SUCCESS) {
382       LOG(ERROR) << "Failed to create bond - status: "
383                  << BtStatusText((const bt_status_t)status);
384       return false;
385     }
386 
387     return true;
388   }
389 
IsMultiAdvertisementSupported()390   bool IsMultiAdvertisementSupported() override {
391     lock_guard<mutex> lock(local_le_features_lock_);
392     return local_le_features_.max_adv_instance >= kMinAdvInstancesForMultiAdv;
393   }
394 
IsDeviceConnected(const std::string & device_address)395   bool IsDeviceConnected(const std::string& device_address) override {
396     lock_guard<mutex> lock(connected_devices_lock_);
397     return connected_devices_.find(device_address) != connected_devices_.end();
398   }
399 
GetTotalNumberOfTrackableAdvertisements()400   int GetTotalNumberOfTrackableAdvertisements() override {
401     lock_guard<mutex> lock(local_le_features_lock_);
402     return local_le_features_.total_trackable_advertisers;
403   }
404 
IsOffloadedFilteringSupported()405   bool IsOffloadedFilteringSupported() override {
406     lock_guard<mutex> lock(local_le_features_lock_);
407     return local_le_features_.max_adv_filter_supported >= kMinOffloadedFilters;
408   }
409 
IsOffloadedScanBatchingSupported()410   bool IsOffloadedScanBatchingSupported() override {
411     lock_guard<mutex> lock(local_le_features_lock_);
412     return local_le_features_.scan_result_storage_size >=
413            kMinOffloadedScanStorageBytes;
414   }
415 
GetBondedDevices()416   bool GetBondedDevices() override {
417     int status =
418         hal::BluetoothInterface::Get()->GetHALInterface()->get_adapter_property(
419             BT_PROPERTY_ADAPTER_BONDED_DEVICES);
420     if (status != BT_STATUS_SUCCESS) {
421       LOG(ERROR) << "Failed to get bonded devices. Status: "
422                  << BtStatusText(static_cast<bt_status_t>(status));
423       return false;
424     }
425 
426     return true;
427   }
428 
RemoveBond(const std::string & device_address)429   bool RemoveBond(const std::string& device_address) override {
430     RawAddress addr;
431     if (!RawAddress::FromString(device_address, addr)) {
432       LOG(ERROR) << "Invalid device address given: " << device_address;
433       return false;
434     }
435 
436     int status =
437         hal::BluetoothInterface::Get()->GetHALInterface()->remove_bond(&addr);
438     if (status != BT_STATUS_SUCCESS) {
439       LOG(ERROR) << "Failed to send remove bond - status: "
440                  << BtStatusText(static_cast<bt_status_t>(status));
441       return false;
442     }
443 
444     return true;
445   }
446 
GetRemoteDeviceProperties(const std::string & device_address)447   bool GetRemoteDeviceProperties(const std::string& device_address) override {
448     RawAddress addr;
449     if (!RawAddress::FromString(device_address, addr)) {
450       LOG(ERROR) << "Invalid device address given: " << device_address;
451       return false;
452     }
453 
454     int status = hal::BluetoothInterface::Get()
455                      ->GetHALInterface()
456                      ->get_remote_device_properties(&addr);
457     if (status != BT_STATUS_SUCCESS) {
458       LOG(ERROR) << "Failed to send GetRemoteDeviceProperties - status: "
459                  << BtStatusText((const bt_status_t)status);
460       return false;
461     }
462 
463     return true;
464   }
465 
GetA2dpSinkFactory() const466   A2dpSinkFactory* GetA2dpSinkFactory() const override {
467     return a2dp_sink_factory_.get();
468   }
469 
GetA2dpSourceFactory() const470   A2dpSourceFactory* GetA2dpSourceFactory() const override {
471     return a2dp_source_factory_.get();
472   }
473 
GetAvrcpControlFactory() const474   AvrcpControlFactory* GetAvrcpControlFactory() const override {
475     return avrcp_control_factory_.get();
476   }
477 
GetAvrcpTargetFactory() const478   AvrcpTargetFactory* GetAvrcpTargetFactory() const override {
479     return avrcp_target_factory_.get();
480   }
481 
GetLowEnergyClientFactory() const482   LowEnergyClientFactory* GetLowEnergyClientFactory() const override {
483     return ble_client_factory_.get();
484   }
485 
GetLeAdvertiserFactory() const486   LowEnergyAdvertiserFactory* GetLeAdvertiserFactory() const override {
487     return ble_advertiser_factory_.get();
488   }
489 
GetLeScannerFactory() const490   LowEnergyScannerFactory* GetLeScannerFactory() const override {
491     return ble_scanner_factory_.get();
492   }
493 
GetGattClientFactory() const494   GattClientFactory* GetGattClientFactory() const override {
495     return gatt_client_factory_.get();
496   }
497 
GetGattServerFactory() const498   GattServerFactory* GetGattServerFactory() const override {
499     return gatt_server_factory_.get();
500   }
501 
502   // hal::BluetoothInterface::Observer overrides.
AdapterStateChangedCallback(bt_state_t state)503   void AdapterStateChangedCallback(bt_state_t state) override {
504     LOG(INFO) << "Adapter state changed: " << BtStateText(state);
505 
506     AdapterState prev_state = GetState();
507 
508     switch (state) {
509       case BT_STATE_OFF:
510         state_ = ADAPTER_STATE_OFF;
511         break;
512 
513       case BT_STATE_ON:
514         state_ = ADAPTER_STATE_ON;
515         break;
516 
517       default:
518         NOTREACHED();
519     }
520 
521     NotifyAdapterStateChanged(prev_state, GetState());
522   }
523 
AdapterPropertiesCallback(bt_status_t status,int num_properties,bt_property_t * properties)524   void AdapterPropertiesCallback(bt_status_t status, int num_properties,
525                                  bt_property_t* properties) override {
526     LOG(INFO) << "Adapter properties changed";
527 
528     if (status != BT_STATUS_SUCCESS) {
529       LOG(ERROR) << "status: " << BtStatusText(status);
530 
531       for (int i = 0; i < num_properties; ++i) {
532         bt_property_t* property = properties + i;
533         if (property->type == BT_PROPERTY_ADAPTER_BONDED_DEVICES) {
534           lock_guard<mutex> lock(observers_lock_);
535           for (auto& observer : observers_) {
536             observer.OnGetBondedDevices(this, status, {});
537           }
538         }
539       }
540       return;
541     }
542 
543     for (int i = 0; i < num_properties; i++) {
544       bt_property_t* property = properties + i;
545       switch (property->type) {
546         case BT_PROPERTY_BDADDR: {
547           std::string address =
548               BtAddrString(reinterpret_cast<RawAddress*>(property->val));
549           LOG(INFO) << "Adapter address changed: " << address;
550           address_.Set(address);
551           break;
552         }
553         case BT_PROPERTY_BDNAME: {
554           bt_bdname_t* hal_name = reinterpret_cast<bt_bdname_t*>(property->val);
555           if (hal_name) {
556             std::string name = reinterpret_cast<char*>(hal_name->name);
557             LOG(INFO) << "Adapter name changed: " << name;
558             name_.Set(name);
559           }
560           break;
561         }
562         case BT_PROPERTY_LOCAL_LE_FEATURES: {
563           lock_guard<mutex> lock(local_le_features_lock_);
564           if (property->len != sizeof(bt_local_le_features_t)) {
565             LOG(WARNING) << "Malformed value received for property: "
566                          << "BT_PROPERTY_LOCAL_LE_FEATURES";
567             break;
568           }
569           bt_local_le_features_t* features =
570               reinterpret_cast<bt_local_le_features_t*>(property->val);
571           memcpy(&local_le_features_, features, sizeof(*features));
572           LOG(INFO) << "Supported LE features updated";
573           break;
574         }
575         case BT_PROPERTY_ADAPTER_BONDED_DEVICES: {
576           if (property->len < 0) {
577             NOTREACHED() << "Negative property length";
578             break;
579           }
580           auto addrs = reinterpret_cast<const RawAddress*>(property->val);
581           if (property->len % sizeof(addrs[0]) != 0) {
582             LOG(ERROR) << "Invalid property length: " << property->len;
583             // TODO(bcf): Seems to be a bug where we hit this somewhat
584             // frequently.
585             break;
586           }
587           std::vector<std::string> str_addrs;
588 
589           for (size_t i = 0; i < property->len / sizeof(addrs[0]); ++i)
590             str_addrs.push_back(BtAddrString(addrs + i));
591 
592           lock_guard<mutex> lock(observers_lock_);
593           for (auto& observer : observers_) {
594             observer.OnGetBondedDevices(this, status, str_addrs);
595           }
596           break;
597         }
598         default:
599           VLOG(1) << "Unhandled adapter property: "
600                   << BtPropertyText(property->type);
601           break;
602       }
603 
604       // TODO(armansito): notify others of the updated properties
605     }
606   }
607 
RemoteDevicePropertiesCallback(bt_status_t status,RawAddress * remote_bdaddr,int num_properties,bt_property_t * properties)608   void RemoteDevicePropertiesCallback(bt_status_t status,
609                                       RawAddress* remote_bdaddr,
610                                       int num_properties,
611                                       bt_property_t* properties) override {
612     std::string device_address = BtAddrString(remote_bdaddr);
613     if (status != BT_STATUS_SUCCESS) {
614       lock_guard<mutex> lock(observers_lock_);
615       for (auto& observer : observers_) {
616         observer.OnGetRemoteDeviceProperties(this, status, device_address,
617                                              RemoteDeviceProps());
618       }
619       return;
620     }
621 
622     RemoteDeviceProps props =
623         ParseRemoteDeviceProps(num_properties, properties);
624 
625     std::string address = BtAddrString(remote_bdaddr);
626     props.set_address(address);
627 
628     lock_guard<mutex> lock(observers_lock_);
629     for (auto& observer : observers_) {
630       observer.OnGetRemoteDeviceProperties(this, status, device_address, props);
631     }
632   }
633 
DeviceFoundCallback(int num_properties,bt_property_t * properties)634   void DeviceFoundCallback(int num_properties,
635                            bt_property_t* properties) override {
636     RemoteDeviceProps props =
637         ParseRemoteDeviceProps(num_properties, properties);
638 
639     lock_guard<mutex> lock(observers_lock_);
640     for (auto& observer : observers_) {
641       observer.OnDeviceFound(this, props);
642     }
643   }
644 
DiscoveryStateChangedCallback(bt_discovery_state_t state)645   void DiscoveryStateChangedCallback(bt_discovery_state_t state) override {
646     bool enabled = false;
647     switch (state) {
648       case BT_DISCOVERY_STOPPED:
649         enabled = false;
650         break;
651       case BT_DISCOVERY_STARTED:
652         enabled = true;
653         break;
654       default:
655         NOTREACHED();
656     }
657 
658     for (auto& observer : observers_) {
659       observer.OnScanEnableChanged(this, enabled);
660     }
661   }
662 
SSPRequestCallback(RawAddress * remote_bdaddr,bt_bdname_t * bd_name,uint32_t cod,bt_ssp_variant_t pairing_variant,uint32_t pass_key)663   void SSPRequestCallback(RawAddress* remote_bdaddr, bt_bdname_t* bd_name,
664                           uint32_t cod, bt_ssp_variant_t pairing_variant,
665                           uint32_t pass_key) override {
666     std::string device_address = BtAddrString(remote_bdaddr);
667     std::string name = reinterpret_cast<char*>(bd_name->name);
668 
669     lock_guard<mutex> lock(observers_lock_);
670     for (auto& observer : observers_) {
671       observer.OnSspRequest(this, device_address, name, cod, pairing_variant,
672                             pass_key);
673     }
674   }
675 
BondStateChangedCallback(bt_status_t status,RawAddress * remote_bdaddr,bt_bond_state_t state)676   void BondStateChangedCallback(bt_status_t status, RawAddress* remote_bdaddr,
677                                 bt_bond_state_t state) override {
678     std::string device_address = BtAddrString(remote_bdaddr);
679 
680     lock_guard<mutex> lock(observers_lock_);
681     for (auto& observer : observers_) {
682       observer.OnBondStateChanged(this, status, device_address, state);
683     }
684   }
685 
AclStateChangedCallback(bt_status_t status,const RawAddress & remote_bdaddr,bt_acl_state_t state,bt_hci_error_code_t hci_reason)686   void AclStateChangedCallback(bt_status_t status,
687                                const RawAddress& remote_bdaddr,
688                                bt_acl_state_t state,
689                                bt_hci_error_code_t hci_reason) override {
690     std::string device_address = BtAddrString(&remote_bdaddr);
691     bool connected = (state == BT_ACL_STATE_CONNECTED);
692     LOG(INFO) << "ACL state changed: " << device_address
693               << " - connected: " << (connected ? "true" : "false");
694 
695     // If this is reported with an error status, I suppose the best thing we can
696     // do is to log it and ignore the event.
697     if (status != BT_STATUS_SUCCESS) {
698       LOG(ERROR) << "status: " << BtStatusText(status);
699       return;
700     }
701 
702     // Introduce a scope to manage |connected_devices_lock_| with RAII.
703     {
704       lock_guard<mutex> lock(connected_devices_lock_);
705       if (connected)
706         connected_devices_.insert(device_address);
707       else
708         connected_devices_.erase(device_address);
709     }
710 
711     lock_guard<mutex> lock(observers_lock_);
712     for (auto& observer : observers_) {
713       observer.OnDeviceConnectionStateChanged(this, device_address, connected);
714     }
715   }
716 
717   // Sends a request to set the given HAL adapter property type and value.
SetAdapterProperty(bt_property_type_t type,void * value,int length)718   bool SetAdapterProperty(bt_property_type_t type, void* value, int length) {
719     CHECK(length > 0);
720     CHECK(value);
721 
722     bt_property_t property;
723     property.len = length;
724     property.val = value;
725     property.type = type;
726 
727     int status =
728         hal::BluetoothInterface::Get()->GetHALInterface()->set_adapter_property(
729             &property);
730     if (status != BT_STATUS_SUCCESS) {
731       VLOG(1) << "Failed to set property";
732       return false;
733     }
734 
735     return true;
736   }
737 
738   // Helper for invoking the AdapterStateChanged observer method.
NotifyAdapterStateChanged(AdapterState prev_state,AdapterState new_state)739   void NotifyAdapterStateChanged(AdapterState prev_state,
740                                  AdapterState new_state) {
741     if (prev_state == new_state) return;
742 
743     lock_guard<mutex> lock(observers_lock_);
744     for (auto& observer : observers_) {
745       observer.OnAdapterStateChanged(this, prev_state, new_state);
746     }
747   }
748 
749  private:
750   // The current adapter state.
751   std::atomic<AdapterState> state_;
752 
753   // The Bluetooth device address of the local adapter in string from
754   // (i.e.. XX:XX:XX:XX:XX:XX)
755   util::AtomicString address_;
756 
757   // The current local adapter name.
758   util::AtomicString name_;
759 
760   // The current set of supported LE features as obtained from the stack. The
761   // values here are all initially set to 0 and updated when the corresponding
762   // adapter property has been received from the stack.
763   std::mutex local_le_features_lock_;
764   bt_local_le_features_t local_le_features_;
765 
766   // List of observers that are interested in notifications from us.
767   std::mutex observers_lock_;
768   btbase::AbstractObserverList<Adapter::Observer> observers_;
769 
770   // List of devices addresses that are currently connected.
771   std::mutex connected_devices_lock_;
772   std::unordered_set<std::string> connected_devices_;
773 
774   // Factory used to create per-app A2dpSink instances.
775   std::unique_ptr<A2dpSinkFactory> a2dp_sink_factory_;
776 
777   // Factory used to create per-app A2dpSource instances.
778   std::unique_ptr<A2dpSourceFactory> a2dp_source_factory_;
779 
780   // Factory used to create per-app AvrcpControl instances.
781   std::unique_ptr<AvrcpControlFactory> avrcp_control_factory_;
782 
783   // Factory used to create per-app AvrcpTarget instances.
784   std::unique_ptr<AvrcpTargetFactory> avrcp_target_factory_;
785 
786   // Factory used to create per-app LowEnergyClient instances.
787   std::unique_ptr<LowEnergyClientFactory> ble_client_factory_;
788 
789   // Factory used to create per-app LeAdvertiser instances.
790   std::unique_ptr<LowEnergyAdvertiserFactory> ble_advertiser_factory_;
791 
792   // Factory used to create per-app LeScanner instances.
793   std::unique_ptr<LowEnergyScannerFactory> ble_scanner_factory_;
794 
795   // Factory used to create per-app GattClient instances.
796   std::unique_ptr<GattClientFactory> gatt_client_factory_;
797 
798   // Factory used to create per-app GattServer instances.
799   std::unique_ptr<GattServerFactory> gatt_server_factory_;
800 
801   DISALLOW_COPY_AND_ASSIGN(AdapterImpl);
802 };
803 
804 // static
Create()805 std::unique_ptr<Adapter> Adapter::Create() {
806   return std::unique_ptr<Adapter>(new AdapterImpl());
807 }
808 
809 }  // namespace bluetooth
810