summaryrefslogtreecommitdiffstats
path: root/components/proximity_auth/ble/bluetooth_low_energy_connection.cc
blob: 11b4a2fd69478aab6b3d6e525b92f2d33fe3bb50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/proximity_auth/ble/bluetooth_low_energy_connection.h"

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "components/proximity_auth/ble/bluetooth_low_energy_characteristics_finder.h"
#include "components/proximity_auth/ble/fake_wire_message.h"
#include "components/proximity_auth/connection_finder.h"
#include "components/proximity_auth/logging/logging.h"
#include "components/proximity_auth/wire_message.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_gatt_characteristic.h"
#include "device/bluetooth/bluetooth_gatt_connection.h"
#include "device/bluetooth/bluetooth_gatt_notify_session.h"
#include "device/bluetooth/bluetooth_uuid.h"

using device::BluetoothAdapter;
using device::BluetoothDevice;
using device::BluetoothGattConnection;
using device::BluetoothGattService;
using device::BluetoothGattCharacteristic;
using device::BluetoothGattNotifySession;
using device::BluetoothUUID;

namespace proximity_auth {
namespace {

// Deprecated signal send as the first byte in send byte operations.
const int kFirstByteZero = 0;

// The maximum number of bytes written in a remote characteristic with a single
// request.
const int kMaxChunkSize = 100;

}  // namespace

BluetoothLowEnergyConnection::BluetoothLowEnergyConnection(
    const RemoteDevice& device,
    scoped_refptr<device::BluetoothAdapter> adapter,
    const BluetoothUUID remote_service_uuid,
    const BluetoothUUID to_peripheral_char_uuid,
    const BluetoothUUID from_peripheral_char_uuid,
    scoped_ptr<BluetoothGattConnection> gatt_connection,
    int max_number_of_write_attempts)
    : Connection(device),
      adapter_(adapter),
      remote_service_({remote_service_uuid, ""}),
      to_peripheral_char_({to_peripheral_char_uuid, ""}),
      from_peripheral_char_({from_peripheral_char_uuid, ""}),
      gatt_connection_(gatt_connection.Pass()),
      sub_status_(SubStatus::DISCONNECTED),
      receiving_bytes_(false),
      write_remote_characteristic_pending_(false),
      max_number_of_write_attempts_(max_number_of_write_attempts),
      max_chunk_size_(kMaxChunkSize),
      weak_ptr_factory_(this) {
  DCHECK(adapter_);
  DCHECK(adapter_->IsInitialized());

  start_time_ = base::TimeTicks::Now();
  adapter_->AddObserver(this);
}

BluetoothLowEnergyConnection::~BluetoothLowEnergyConnection() {
  Disconnect();
  if (adapter_) {
    adapter_->RemoveObserver(this);
    adapter_ = NULL;
  }
}

void BluetoothLowEnergyConnection::Connect() {
  if (gatt_connection_ && gatt_connection_->IsConnected()) {
    OnGattConnectionCreated(gatt_connection_.Pass());
    return;
  }

  BluetoothDevice* remote_device = GetRemoteDevice();
  if (remote_device) {
    SetSubStatus(SubStatus::WAITING_GATT_CONNECTION);
    remote_device->CreateGattConnection(
        base::Bind(&BluetoothLowEnergyConnection::OnGattConnectionCreated,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothLowEnergyConnection::OnCreateGattConnectionError,
                   weak_ptr_factory_.GetWeakPtr()));
  }
}

void BluetoothLowEnergyConnection::Disconnect() {
  if (sub_status_ != SubStatus::DISCONNECTED) {
    ClearWriteRequestsQueue();
    StopNotifySession();
    SetSubStatus(SubStatus::DISCONNECTED);
    if (gatt_connection_) {
      PA_LOG(INFO) << "Disconnect from device "
                   << gatt_connection_->GetDeviceAddress();

      // Destroying BluetoothGattConnection also disconnects it.
      gatt_connection_.reset();
    }
  }
}

void BluetoothLowEnergyConnection::OnDisconnected() {
  PA_LOG(INFO) << "Disconnected.";
}

void BluetoothLowEnergyConnection::OnDisconnectError() {
  PA_LOG(WARNING) << "Disconnection failed.";
}

void BluetoothLowEnergyConnection::SetSubStatus(SubStatus new_sub_status) {
  sub_status_ = new_sub_status;

  // Sets the status of parent class proximity_auth::Connection accordingly.
  if (new_sub_status == SubStatus::CONNECTED) {
    SetStatus(CONNECTED);
  } else if (new_sub_status == SubStatus::DISCONNECTED) {
    SetStatus(DISCONNECTED);
  } else {
    SetStatus(IN_PROGRESS);
  }
}

void BluetoothLowEnergyConnection::SendMessageImpl(
    scoped_ptr<WireMessage> message) {
  PA_LOG(INFO) << "Sending message " << message->Serialize();

  std::string serialized_msg = message->Serialize();

  WriteRequest write_request = BuildWriteRequest(
      ToByteVector(static_cast<uint32>(ControlSignal::kSendSignal)),
      ToByteVector(static_cast<uint32>(serialized_msg.size())), false);
  WriteRemoteCharacteristic(write_request);

  // Each chunk has to include a deprecated signal: |kFirstByteZero| as the
  // first byte.
  int chunk_size = max_chunk_size_ - 1;
  std::vector<uint8> kFirstByteZeroVector;
  kFirstByteZeroVector.push_back(static_cast<uint8>(kFirstByteZero));

  int message_size = static_cast<int>(serialized_msg.size());
  int start_index = 0;
  while (start_index < message_size) {
    int end_index = (start_index + chunk_size) <= message_size
                        ? (start_index + chunk_size)
                        : message_size;
    bool is_last_write_request = (end_index == message_size);
    write_request = BuildWriteRequest(
        kFirstByteZeroVector,
        std::vector<uint8>(serialized_msg.begin() + start_index,
                           serialized_msg.begin() + end_index),
        is_last_write_request);
    WriteRemoteCharacteristic(write_request);
    start_index = end_index;
  }
}

// Changes in the GATT connection with the remote device should be observed
// here. If the GATT connection is dropped, we should call Disconnect() anyway,
// so the object can notify its observers put itself in the right state.
void BluetoothLowEnergyConnection::DeviceChanged(BluetoothAdapter* adapter,
                                                 BluetoothDevice* device) {
  if (device && device->GetAddress() == GetRemoteDeviceAddress() &&
      !device->IsConnected()) {
    PA_LOG(INFO) << "GATT connection dropped " << GetRemoteDeviceAddress();
    Disconnect();
  }
}

void BluetoothLowEnergyConnection::DeviceRemoved(BluetoothAdapter* adapter,
                                                 BluetoothDevice* device) {
  if (device && device->GetAddress() == GetRemoteDeviceAddress()) {
    PA_LOG(INFO) << "Device removed " << GetRemoteDeviceAddress();
    Disconnect();
  }
}

void BluetoothLowEnergyConnection::GattCharacteristicValueChanged(
    BluetoothAdapter* adapter,
    BluetoothGattCharacteristic* characteristic,
    const std::vector<uint8>& value) {
  DCHECK_EQ(adapter, adapter_.get());

  PA_LOG(INFO) << "Characteristic value changed: "
               << characteristic->GetUUID().canonical_value();

  if (characteristic->GetIdentifier() == from_peripheral_char_.id) {
    if (receiving_bytes_) {
      // Ignoring the first byte, as it contains a deprecated signal.
      const std::string bytes(value.begin() + 1, value.end());
      incoming_bytes_buffer_.append(bytes);
      if (incoming_bytes_buffer_.size() >= expected_number_of_incoming_bytes_) {
        OnBytesReceived(incoming_bytes_buffer_);
        receiving_bytes_ = false;
      }
      return;
    }

    if (value.size() < 4) {
      PA_LOG(WARNING) << "Incoming data corrupted, no signal found.";
      return;
    }

    const ControlSignal signal = static_cast<ControlSignal>(ToUint32(value));
    switch (signal) {
      case ControlSignal::kInvitationResponseSignal:
        if (sub_status() == SubStatus::WAITING_RESPONSE_SIGNAL)
          CompleteConnection();
        break;
      case ControlSignal::kInviteToConnectSignal:
        break;
      case ControlSignal::kSendSignal: {
        if (value.size() < 8) {
          PA_LOG(WARNING)
              << "Incoming data corrupted, expected message size not found.";
          return;
        }
        std::vector<uint8> size(value.begin() + 4, value.end());
        expected_number_of_incoming_bytes_ =
            static_cast<size_t>(ToUint32(size));
        receiving_bytes_ = true;
        incoming_bytes_buffer_.clear();
        break;
      }
      case ControlSignal::kDisconnectSignal:
        Disconnect();
        break;
    }
  }
}

BluetoothLowEnergyConnection::WriteRequest::WriteRequest(
    const std::vector<uint8>& val,
    bool flag)
    : value(val),
      is_last_write_for_wire_message(flag),
      number_of_failed_attempts(0) {
}

BluetoothLowEnergyConnection::WriteRequest::~WriteRequest() {
}

scoped_ptr<WireMessage> BluetoothLowEnergyConnection::DeserializeWireMessage(
    bool* is_incomplete_message) {
  return FakeWireMessage::Deserialize(received_bytes(), is_incomplete_message);
}

void BluetoothLowEnergyConnection::CompleteConnection() {
  PA_LOG(INFO) << "Connection completed. Time elapsed: "
               << base::TimeTicks::Now() - start_time_;
  SetSubStatus(SubStatus::CONNECTED);
}

void BluetoothLowEnergyConnection::OnCreateGattConnectionError(
    device::BluetoothDevice::ConnectErrorCode error_code) {
  PA_LOG(WARNING) << "Error creating GATT connection to "
                  << remote_device().bluetooth_address
                  << "error code: " << error_code;
  Disconnect();
}

void BluetoothLowEnergyConnection::OnGattConnectionCreated(
    scoped_ptr<device::BluetoothGattConnection> gatt_connection) {
  gatt_connection_ = gatt_connection.Pass();
  SetSubStatus(SubStatus::WAITING_CHARACTERISTICS);
  characteristic_finder_.reset(CreateCharacteristicsFinder(
      base::Bind(&BluetoothLowEnergyConnection::OnCharacteristicsFound,
                 weak_ptr_factory_.GetWeakPtr()),
      base::Bind(&BluetoothLowEnergyConnection::OnCharacteristicsFinderError,
                 weak_ptr_factory_.GetWeakPtr())));
}

BluetoothLowEnergyCharacteristicsFinder*
BluetoothLowEnergyConnection::CreateCharacteristicsFinder(
    const BluetoothLowEnergyCharacteristicsFinder::SuccessCallback&
        success_callback,
    const BluetoothLowEnergyCharacteristicsFinder::ErrorCallback&
        error_callback) {
  return new BluetoothLowEnergyCharacteristicsFinder(
      adapter_, GetRemoteDevice(), remote_service_, to_peripheral_char_,
      from_peripheral_char_, success_callback, error_callback);
}

void BluetoothLowEnergyConnection::OnCharacteristicsFound(
    const RemoteAttribute& service,
    const RemoteAttribute& to_peripheral_char,
    const RemoteAttribute& from_peripheral_char) {
  remote_service_ = service;
  to_peripheral_char_ = to_peripheral_char;
  from_peripheral_char_ = from_peripheral_char;

  SetSubStatus(SubStatus::CHARACTERISTICS_FOUND);
  StartNotifySession();
}

void BluetoothLowEnergyConnection::OnCharacteristicsFinderError(
    const RemoteAttribute& to_peripheral_char,
    const RemoteAttribute& from_peripheral_char) {
  PA_LOG(WARNING) << "Connection error, missing characteristics for SmartLock "
                     "service.\n"
                  << (to_peripheral_char.id.empty()
                          ? to_peripheral_char.uuid.canonical_value()
                          : "")
                  << (from_peripheral_char.id.empty()
                          ? ", " + from_peripheral_char.uuid.canonical_value()
                          : "") << " not found.";

  Disconnect();
}

void BluetoothLowEnergyConnection::StartNotifySession() {
  if (sub_status() == SubStatus::CHARACTERISTICS_FOUND) {
    BluetoothGattCharacteristic* characteristic =
        GetGattCharacteristic(from_peripheral_char_.id);
    DCHECK(characteristic);

    SetSubStatus(SubStatus::WAITING_NOTIFY_SESSION);
    characteristic->StartNotifySession(
        base::Bind(&BluetoothLowEnergyConnection::OnNotifySessionStarted,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothLowEnergyConnection::OnNotifySessionError,
                   weak_ptr_factory_.GetWeakPtr()));
  }
}

void BluetoothLowEnergyConnection::OnNotifySessionError(
    BluetoothGattService::GattErrorCode error) {
  PA_LOG(WARNING) << "Error starting notification session: " << error;
  Disconnect();
}

void BluetoothLowEnergyConnection::OnNotifySessionStarted(
    scoped_ptr<BluetoothGattNotifySession> notify_session) {
  PA_LOG(INFO) << "Notification session started "
               << notify_session->GetCharacteristicIdentifier();

  SetSubStatus(SubStatus::NOTIFY_SESSION_READY);
  notify_session_ = notify_session.Pass();

  // Sends an invite to connect signal if ready.
  SendInviteToConnectSignal();
}

void BluetoothLowEnergyConnection::StopNotifySession() {
  if (notify_session_) {
    notify_session_->Stop(base::Bind(&base::DoNothing));
    notify_session_.reset();
  }
}

void BluetoothLowEnergyConnection::SendInviteToConnectSignal() {
  if (sub_status() == SubStatus::NOTIFY_SESSION_READY) {
    PA_LOG(INFO) << "Sending invite to connect signal";
    SetSubStatus(SubStatus::WAITING_RESPONSE_SIGNAL);

    WriteRequest write_request = BuildWriteRequest(
        ToByteVector(
            static_cast<uint32>(ControlSignal::kInviteToConnectSignal)),
        std::vector<uint8>(), false);

    WriteRemoteCharacteristic(write_request);
  }
}

void BluetoothLowEnergyConnection::WriteRemoteCharacteristic(
    WriteRequest request) {
  write_requests_queue_.push(request);
  ProcessNextWriteRequest();
}

void BluetoothLowEnergyConnection::ProcessNextWriteRequest() {
  BluetoothGattCharacteristic* characteristic =
      GetGattCharacteristic(to_peripheral_char_.id);
  if (!write_requests_queue_.empty() && !write_remote_characteristic_pending_ &&
      characteristic) {
    write_remote_characteristic_pending_ = true;
    WriteRequest next_request = write_requests_queue_.front();
    characteristic->WriteRemoteCharacteristic(
        next_request.value,
        base::Bind(&BluetoothLowEnergyConnection::OnRemoteCharacteristicWritten,
                   weak_ptr_factory_.GetWeakPtr(),
                   next_request.is_last_write_for_wire_message),
        base::Bind(
            &BluetoothLowEnergyConnection::OnWriteRemoteCharacteristicError,
            weak_ptr_factory_.GetWeakPtr(),
            next_request.is_last_write_for_wire_message));
  }
}

void BluetoothLowEnergyConnection::OnRemoteCharacteristicWritten(
    bool run_did_send_message_callback) {
  write_remote_characteristic_pending_ = false;
  // TODO(sacomoto): Actually pass the current message to the observer.
  if (run_did_send_message_callback)
    OnDidSendMessage(FakeWireMessage(""), true);

  // Removes the top of queue (already processed) and process the next request.
  DCHECK(!write_requests_queue_.empty());
  write_requests_queue_.pop();
  ProcessNextWriteRequest();
}

void BluetoothLowEnergyConnection::OnWriteRemoteCharacteristicError(
    bool run_did_send_message_callback,
    BluetoothGattService::GattErrorCode error) {
  PA_LOG(WARNING) << "Error " << error << " writing characteristic: "
                  << to_peripheral_char_.uuid.canonical_value();
  write_remote_characteristic_pending_ = false;
  // TODO(sacomoto): Actually pass the current message to the observer.
  if (run_did_send_message_callback)
    OnDidSendMessage(FakeWireMessage(""), false);

  // Increases the number of failed attempts and retry.
  DCHECK(!write_requests_queue_.empty());
  if (++write_requests_queue_.front().number_of_failed_attempts >=
      max_number_of_write_attempts_) {
    Disconnect();
    return;
  }
  ProcessNextWriteRequest();
}

BluetoothLowEnergyConnection::WriteRequest
BluetoothLowEnergyConnection::BuildWriteRequest(
    const std::vector<uint8>& signal,
    const std::vector<uint8>& bytes,
    bool is_last_write_for_wire_message) {
  std::vector<uint8> value(signal.begin(), signal.end());
  value.insert(value.end(), bytes.begin(), bytes.end());
  return WriteRequest(value, is_last_write_for_wire_message);
}

void BluetoothLowEnergyConnection::ClearWriteRequestsQueue() {
  while (!write_requests_queue_.empty())
    write_requests_queue_.pop();
}

const std::string& BluetoothLowEnergyConnection::GetRemoteDeviceAddress() {
  return remote_device().bluetooth_address;
}

BluetoothDevice* BluetoothLowEnergyConnection::GetRemoteDevice() {
  // It's not possible to simply use
  // |adapter_->GetDevice(GetRemoteDeviceAddress())| to find the device with MAC
  // address |GetRemoteDeviceAddress()|. For paired devices,
  // BluetoothAdapter::GetDevice(XXX) searches for the temporary MAC address
  // XXX, whereas |GetRemoteDeviceAddress()| is the real MAC address. This is a
  // bug in the way device::BluetoothAdapter is storing the devices (see
  // crbug.com/497841).
  std::vector<BluetoothDevice*> devices = adapter_->GetDevices();
  for (const auto& device : devices) {
    if (device->GetAddress() == GetRemoteDeviceAddress())
      return device;
  }

  return nullptr;
}

BluetoothGattService* BluetoothLowEnergyConnection::GetRemoteService() {
  BluetoothDevice* remote_device = GetRemoteDevice();
  if (!remote_device) {
    PA_LOG(WARNING) << "Remote device not found.";
    return NULL;
  }
  if (remote_service_.id.empty()) {
    std::vector<BluetoothGattService*> services =
        remote_device->GetGattServices();
    for (const auto& service : services)
      if (service->GetUUID() == remote_service_.uuid) {
        remote_service_.id = service->GetIdentifier();
        break;
      }
  }
  return remote_device->GetGattService(remote_service_.id);
}

BluetoothGattCharacteristic*
BluetoothLowEnergyConnection::GetGattCharacteristic(
    const std::string& gatt_characteristic) {
  BluetoothGattService* remote_service = GetRemoteService();
  if (!remote_service) {
    PA_LOG(WARNING) << "Remote service not found.";
    return NULL;
  }
  return remote_service->GetCharacteristic(gatt_characteristic);
}

// TODO(sacomoto): make this robust to byte ordering in both sides of the
// SmartLock BLE socket.
uint32 BluetoothLowEnergyConnection::ToUint32(const std::vector<uint8>& bytes) {
  return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);
}

// TODO(sacomoto): make this robust to byte ordering in both sides of the
// SmartLock BLE socket.
const std::vector<uint8> BluetoothLowEnergyConnection::ToByteVector(
    const uint32 value) {
  std::vector<uint8> bytes(4, 0);
  bytes[0] = static_cast<uint8>(value);
  bytes[1] = static_cast<uint8>(value >> 8);
  bytes[2] = static_cast<uint8>(value >> 16);
  bytes[3] = static_cast<uint8>(value >> 24);
  return bytes;
}

}  // namespace proximity_auth