File: arc_floss_bridge.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (644 lines) | stat: -rw-r--r-- 24,201 bytes parent folder | download | duplicates (6)
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/arc/bluetooth/arc_floss_bridge.h"

#include <bluetooth/bluetooth.h>
#include <bluetooth/l2cap.h>
#include <bluetooth/rfcomm.h>

#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "chromeos/ash/experiences/arc/bluetooth/bluetooth_type_converters.h"
#include "chromeos/ash/experiences/arc/session/arc_bridge_service.h"
#include "device/bluetooth/bluetooth_socket.h"
#include "device/bluetooth/floss/bluetooth_device_floss.h"
#include "device/bluetooth/floss/floss_dbus_manager.h"
#include "device/bluetooth/floss/floss_sdp_types.h"
#include "device/bluetooth/floss/floss_socket_manager.h"

using device::BluetoothUUID;
using floss::BluetoothDeviceFloss;

namespace arc {

ArcFlossBridge::ArcFlossBridge(content::BrowserContext* context,
                               ArcBridgeService* bridge_service)
    : ArcBluetoothBridge(context, bridge_service) {}

ArcFlossBridge::~ArcFlossBridge() {
  if (GetAdapter() && GetAdapter()->IsPowered() &&
      floss::FlossDBusManager::Get()->GetAdapterClient()->HasObserver(this)) {
    floss::FlossDBusManager::Get()->GetAdapterClient()->RemoveObserver(this);
  }
}

floss::BluetoothAdapterFloss* ArcFlossBridge::GetAdapter() const {
  return static_cast<floss::BluetoothAdapterFloss*>(bluetooth_adapter_.get());
}

void ArcFlossBridge::HandlePoweredOn() {
  if (!floss::FlossDBusManager::Get()->GetAdapterClient()->HasObserver(this)) {
    floss::FlossDBusManager::Get()->GetAdapterClient()->AddObserver(this);
  }
}

void ArcFlossBridge::OnSdpSearchResult(mojom::BluetoothAddressPtr remote_addr,
                                       const device::BluetoothUUID& target_uuid,
                                       floss::DBusResult<bool> result) {
  if (!result.has_value()) {
    OnGetServiceRecordsError(
        std::move(remote_addr), target_uuid,
        bluez::BluetoothServiceRecordBlueZ::ErrorCode::UNKNOWN);
    return;
  }

  if (!*result) {
    OnGetServiceRecordsError(
        std::move(remote_addr), target_uuid,
        bluez::BluetoothServiceRecordBlueZ::ErrorCode::UNKNOWN);
    return;
  }
}

void ArcFlossBridge::GetSdpRecords(mojom::BluetoothAddressPtr remote_addr,
                                   const BluetoothUUID& target_uuid) {
  if (!AdapterReadyAndRegistered()) {
    OnGetServiceRecordsError(
        std::move(remote_addr), target_uuid,
        bluez::BluetoothServiceRecordBlueZ::ErrorCode::ERROR_ADAPTER_NOT_READY);
    return;
  }

  const floss::FlossDeviceId remote_device = floss::FlossDeviceId(
      {.address = remote_addr->To<std::string>(), .name = ""});
  floss::ResponseCallback<bool> response_callback = base::BindOnce(
      &ArcFlossBridge::OnSdpSearchResult, weak_factory_.GetWeakPtr(),
      std::move(remote_addr), target_uuid);

  floss::FlossDBusManager::Get()->GetAdapterClient()->SdpSearch(
      std::move(response_callback), remote_device, target_uuid);
}

void ArcFlossBridge::CreateSdpRecordComplete(device::BluetoothUUID uuid,
                                             floss::DBusResult<bool> result) {
  if (!result.has_value()) {
    arc::mojom::BluetoothCreateSdpRecordResultPtr callback_result =
        arc::mojom::BluetoothCreateSdpRecordResult::New();
    callback_result->status = mojom::BluetoothStatus::FAIL;
    CompleteCreateSdpRecord(uuid, std::move(callback_result));
    return;
  }

  if (!*result) {
    arc::mojom::BluetoothCreateSdpRecordResultPtr callback_result =
        arc::mojom::BluetoothCreateSdpRecordResult::New();
    callback_result->status = mojom::BluetoothStatus::FAIL;
    CompleteCreateSdpRecord(uuid, std::move(callback_result));
    return;
  }
}

void ArcFlossBridge::CreateSdpRecord(mojom::BluetoothSdpRecordPtr record_mojo,
                                     CreateSdpRecordCallback callback) {
  if (!AdapterReadyAndRegistered()) {
    arc::mojom::BluetoothCreateSdpRecordResultPtr result =
        arc::mojom::BluetoothCreateSdpRecordResult::New();
    result->status = mojom::BluetoothStatus::NOT_READY;
    std::move(callback).Run(std::move(result));
    return;
  }
  const floss::BtSdpRecord sdp_record =
      mojo::TypeConverter<floss::BtSdpRecord,
                          bluez::BluetoothServiceRecordBlueZ>::
          Convert(mojo::TypeConverter<
                  bluez::BluetoothServiceRecordBlueZ,
                  mojom::BluetoothSdpRecordPtr>::Convert(record_mojo));
  const std::optional<device::BluetoothUUID> uuid =
      floss::GetUUIDFromSdpRecord(sdp_record);
  if (!uuid.has_value()) {
    arc::mojom::BluetoothCreateSdpRecordResultPtr result =
        arc::mojom::BluetoothCreateSdpRecordResult::New();
    result->status = mojom::BluetoothStatus::PARM_INVALID;
    std::move(callback).Run(std::move(result));
    return;
  }
  create_sdp_record_callbacks_.insert_or_assign(*uuid, std::move(callback));

  floss::ResponseCallback<bool> response_callback =
      base::BindOnce(&ArcFlossBridge::CreateSdpRecordComplete,
                     weak_factory_.GetWeakPtr(), *uuid);
  floss::FlossDBusManager::Get()->GetAdapterClient()->CreateSdpRecord(
      std::move(response_callback), sdp_record);
}

void ArcFlossBridge::RemoveSdpRecordComplete(RemoveSdpRecordCallback callback,
                                             floss::DBusResult<bool> result) {
  if (!result.has_value()) {
    std::move(callback).Run(arc::mojom::BluetoothStatus::FAIL);
    return;
  }

  if (!*result) {
    std::move(callback).Run(arc::mojom::BluetoothStatus::FAIL);
    return;
  }

  std::move(callback).Run(arc::mojom::BluetoothStatus::SUCCESS);
}

void ArcFlossBridge::RemoveSdpRecord(uint32_t service_handle,
                                     RemoveSdpRecordCallback callback) {
  if (!AdapterReadyAndRegistered()) {
    std::move(callback).Run(arc::mojom::BluetoothStatus::NOT_READY);
    return;
  }

  floss::ResponseCallback<bool> response_callback =
      base::BindOnce(&ArcFlossBridge::RemoveSdpRecordComplete,
                     weak_factory_.GetWeakPtr(), std::move(callback));
  floss::FlossDBusManager::Get()->GetAdapterClient()->RemoveSdpRecord(
      std::move(response_callback), service_handle);
}

namespace {

void OnNoOpBtifResult(
    floss::DBusResult<floss::FlossDBusClient::BtifStatus> result) {}

floss::FlossSocketManager::Security GetSecureFromFlags(
    const mojom::BluetoothSocketFlagsPtr flags) {
  // From Floss's masking logic secure = encrypt+auth
  return (flags->encrypt && flags->auth)
             ? floss::FlossSocketManager::Security::kSecure
             : floss::FlossSocketManager::Security::kInsecure;
}

}  // namespace

void ArcFlossBridge::OnCloseBluetoothListeningSocketComplete(
    BluetoothListeningSocket* socket,
    floss::DBusResult<floss::FlossDBusClient::BtifStatus> result) {
  // We are not going to keep the socket around regardless of whether Floss
  // succeeded, but we give it a chance.
  listening_sockets_.erase(socket);
}

void ArcFlossBridge::CloseBluetoothListeningSocket(
    BluetoothListeningSocket* ptr) {
  if (!listening_sockets_.contains(ptr)) {
    return;
  }

  floss::ResponseCallback<floss::FlossAdapterClient::BtifStatus>
      response_callback = base::BindOnce(
          &ArcFlossBridge::OnCloseBluetoothListeningSocketComplete,
          weak_factory_.GetWeakPtr(), ptr);
  floss::FlossDBusManager::Get()->GetSocketManager()->Close(
      listening_sockets_[ptr].second, std::move(response_callback));
}

void ArcFlossBridge::CloseBluetoothConnectingSocket(
    BluetoothConnectingSocket* ptr) {
  auto found = connecting_sockets_.find(ptr);
  connecting_sockets_.erase(found);
}

void ArcFlossBridge::SdpSearchComplete(
    const floss::FlossDeviceId device,
    const device::BluetoothUUID uuid,
    const std::vector<floss::BtSdpRecord>& records) {
  mojom::BluetoothAddressPtr address =
      mojom::BluetoothAddress::From(device.address);
  std::vector<bluez::BluetoothServiceRecordBlueZ> records_bluez;
  for (const auto& record : records) {
    records_bluez.push_back(
        mojo::TypeConverter<bluez::BluetoothServiceRecordBlueZ,
                            floss::BtSdpRecord>::Convert(record));
    std::optional<floss::BtSdpHeaderOverlay> header =
        GetHeaderOverlayFromSdpRecord(record);
    if (!header.has_value()) {
      continue;
    }
    // This record may be for an L2CAP service, but callers have to specify what
    // protocol they want to use anyway.
    uuid_lookups_.insert_or_assign(
        std::make_pair(device.address, header->rfcomm_channel_number),
        header->uuid);
  }
  OnGetServiceRecordsFinished(std::move(address), uuid, records_bluez);
}

void ArcFlossBridge::SdpRecordCreated(const floss::BtSdpRecord record,
                                      const int32_t handle) {
  const std::optional<device::BluetoothUUID> uuid =
      floss::GetUUIDFromSdpRecord(record);
  if (!uuid.has_value()) {
    return;
  }
  arc::mojom::BluetoothCreateSdpRecordResultPtr callback_result =
      arc::mojom::BluetoothCreateSdpRecordResult::New();
  callback_result->status = mojom::BluetoothStatus::SUCCESS;
  callback_result->service_handle = handle;
  CompleteCreateSdpRecord(*uuid, std::move(callback_result));
}

void ArcFlossBridge::SendCachedDevices() const {
  auto* bluetooth_instance = ARC_GET_INSTANCE_FOR_METHOD(
      arc_bridge_service_->bluetooth(), OnDevicePropertiesChanged);
  if (!bluetooth_instance) {
    return;
  }

  for (const auto* device : bluetooth_adapter_->GetDevices()) {
    const BluetoothDeviceFloss* floss_device =
        static_cast<const BluetoothDeviceFloss*>(device);
    if (!floss_device->HasReadProperties()) {
      VLOG(1) << "Skipping device that hasn't read properties: "
              << floss_device->GetAddress();
      continue;
    }

    // Since a cached device may not be a currently available device, we use
    // OnDevicePropertiesChanged() instead of OnDeviceFound() to avoid trigger
    // the logic of device found in Android.
    bluetooth_instance->OnDevicePropertiesChanged(
        mojom::BluetoothAddress::From(device->GetAddress()),
        GetDeviceProperties(mojom::BluetoothPropertyType::ALL, device));
  }
}

void ArcFlossBridge::StartLEScanImpl() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!bluetooth_adapter_) {
    LOG(DFATAL) << "Bluetooth adapter does not exist.";
    return;
  }

  if (ble_scan_session_) {
    LOG(ERROR) << "LE scan already running.";
    StartLEScanOffTimer();
    scanned_devices_.clear();
    discovery_queue_.Pop();
    return;
  }

  ble_scan_session_ = bluetooth_adapter_->StartLowEnergyScanSession(
      nullptr, weak_factory_.GetWeakPtr());
}

void ArcFlossBridge::ResetLEScanSession() {
  if (ble_scan_session_) {
    ble_scan_session_.reset();
  }
}

bool ArcFlossBridge::IsDiscoveringOrScanning() {
  return discovery_session_ || ble_scan_session_;
}

void ArcFlossBridge::CreateBluetoothListenSocket(
    mojom::BluetoothSocketType type,
    mojom::BluetoothSocketFlagsPtr flags,
    int port,
    ArcFlossBridge::BluetoothSocketListenCallback callback) {
  if (!AdapterReadyAndRegistered()) {
    return;
  }
  if (type != mojom::BluetoothSocketType::TYPE_RFCOMM &&
      type != mojom::BluetoothSocketType::TYPE_L2CAP_LE) {
    std::move(callback).Run(
        mojom::BluetoothStatus::FAIL, /*port=*/0,
        mojo::PendingReceiver<mojom::BluetoothListenSocketClient>());
    return;
  }
  auto sock_wrapper = std::make_unique<BluetoothListeningSocket>();
  sock_wrapper->sock_type = type;
  auto connection_accepted_callback =
      base::BindRepeating(&ArcFlossBridge::OnConnectionAccepted,
                          weak_factory_.GetWeakPtr(), sock_wrapper.get());
  int socket_ready_callback_id = next_socket_ready_callback_id_++;
  socket_ready_callbacks_.insert_or_assign(socket_ready_callback_id,
                                           std::move(callback));
  auto connection_state_changed_callback = base::BindRepeating(
      &ArcFlossBridge::OnConnectionStateChanged, weak_factory_.GetWeakPtr(),
      // TODO(crbug.com/40061562): Remove `UnsafeDanglingUntriaged`
      base::UnsafeDanglingUntriaged(sock_wrapper.get()),
      socket_ready_callback_id);
  floss::ResponseCallback<floss::FlossDBusClient::BtifStatus>
      response_callback =
          base::BindOnce(&ArcFlossBridge::OnCreateListenSocketCallback,
                         weak_factory_.GetWeakPtr(), std::move(sock_wrapper),
                         socket_ready_callback_id);
  switch (type) {
    case mojom::BluetoothSocketType::TYPE_RFCOMM: {
      floss::FlossDBusManager::Get()->GetSocketManager()->ListenUsingRfcommAlt(
          std::nullopt, std::nullopt, port,
          floss::FlossSocketManager::GetRawFlossFlagsFromBluetoothFlags(
              flags->encrypt, flags->auth, flags->auth_mitm,
              flags->auth_16_digit, /*no_sdp=*/true),
          std::move(response_callback),
          std::move(connection_state_changed_callback),
          std::move(connection_accepted_callback));
      break;
    }
    case mojom::BluetoothSocketType::TYPE_L2CAP_LE: {
      floss::FlossDBusManager::Get()->GetSocketManager()->ListenUsingL2capLe(
          GetSecureFromFlags(std::move(flags)), std::move(response_callback),
          std::move(connection_state_changed_callback),
          std::move(connection_accepted_callback));
      break;
    }
    default: {
      return;
    }
  }
}

void ArcFlossBridge::CreateBluetoothConnectSocket(
    mojom::BluetoothSocketType type,
    mojom::BluetoothSocketFlagsPtr flags,
    mojom::BluetoothAddressPtr addr,
    int port,
    ArcFlossBridge::BluetoothSocketConnectCallback callback) {
  if (!AdapterReadyAndRegistered()) {
    return;
  }
  const floss::FlossDeviceId remote_device =
      floss::FlossDeviceId({.address = addr->To<std::string>(), .name = ""});
  auto sock_wrapper = std::make_unique<BluetoothConnectingSocket>();
  sock_wrapper->sock_type = type;
  switch (type) {
    case mojom::BluetoothSocketType::TYPE_RFCOMM: {
      const std::pair<std::string, int32_t> uuid_lookup_key =
          std::make_pair(remote_device.address, port);
      if (!uuid_lookups_.contains(uuid_lookup_key)) {
        std::move(callback).Run(
            mojom::BluetoothStatus::FAIL,
            mojo::PendingReceiver<mojom::BluetoothConnectSocketClient>());
        return;
      }
      floss::FlossDBusManager::Get()->GetSocketManager()->ConnectUsingRfcomm(
          remote_device, uuid_lookups_.at(uuid_lookup_key),
          GetSecureFromFlags(std::move(flags)),
          base::BindOnce(&ArcFlossBridge::OnCreateConnectSocketCallback,
                         weak_factory_.GetWeakPtr(), std::move(sock_wrapper),
                         std::move(callback)));
      break;
    }
    case mojom::BluetoothSocketType::TYPE_L2CAP_LE: {
      floss::FlossDBusManager::Get()->GetSocketManager()->ConnectUsingL2capLe(
          remote_device, port, GetSecureFromFlags(std::move(flags)),
          base::BindOnce(&ArcFlossBridge::OnCreateConnectSocketCallback,
                         weak_factory_.GetWeakPtr(), std::move(sock_wrapper),
                         std::move(callback)));
      break;
    }
    default: {
      std::move(callback).Run(
          mojom::BluetoothStatus::FAIL,
          mojo::PendingReceiver<mojom::BluetoothConnectSocketClient>());
      return;
    }
  }
}

void ArcFlossBridge::OnCreateListenSocketCallback(
    std::unique_ptr<ArcBluetoothBridge::BluetoothListeningSocket> sock_wrapper,
    int socket_ready_callback_id,
    floss::DBusResult<floss::FlossDBusClient::BtifStatus> result) {
  ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper_to_pass =
      sock_wrapper.get();
  listening_sockets_.insert_or_assign(
      sock_wrapper.get(),
      std::make_pair(std::move(sock_wrapper), empty_socket_id_));
  if (!result.has_value()) {
    CompleteListenSocketReady(socket_ready_callback_id,
                              mojom::BluetoothStatus::FAIL,
                              sock_wrapper_to_pass);
    return;
  }

  if (*result != floss::FlossDBusClient::BtifStatus::kSuccess) {
    CompleteListenSocketReady(socket_ready_callback_id,
                              mojom::BluetoothStatus::FAIL,
                              sock_wrapper_to_pass);
    return;
  }
}

void ArcFlossBridge::OnCreateConnectSocketCallback(
    std::unique_ptr<ArcBluetoothBridge::BluetoothConnectingSocket> sock_wrapper,
    ArcFlossBridge::BluetoothSocketConnectCallback callback,
    floss::FlossDBusClient::BtifStatus status,
    std::optional<floss::FlossSocketManager::FlossSocket>&& socket) {
  if (status != floss::FlossDBusClient::BtifStatus::kSuccess) {
    std::move(callback).Run(
        mojom::BluetoothStatus::FAIL,
        mojo::PendingReceiver<mojom::BluetoothConnectSocketClient>());
    return;
  }

  if (!socket || !socket->fd) {
    std::move(callback).Run(
        mojom::BluetoothStatus::FAIL,
        mojo::PendingReceiver<mojom::BluetoothConnectSocketClient>());
    return;
  }

  sock_wrapper->file = std::move(socket->fd.value());
  std::move(callback).Run(mojom::BluetoothStatus::SUCCESS,
                          sock_wrapper->remote.BindNewPipeAndPassReceiver());
  auto connection = mojom::BluetoothSocketConnection::New();
  mojo::ScopedHandle handle = mojo::WrapPlatformHandle(
      mojo::PlatformHandle(std::move(sock_wrapper->file)));
  connection->sock = std::move(handle);
  switch (sock_wrapper->sock_type) {
    case mojom::BluetoothSocketType::TYPE_RFCOMM:
    case mojom::BluetoothSocketType::TYPE_L2CAP_LE:
      connection->addr = mojom::BluetoothAddress::From<std::string>(
          socket->remote_device.address);
      connection->port = socket->port;
      break;
    default:
      LOG(ERROR) << "Unknown socket type " << sock_wrapper->sock_type;
      return;
  }
  sock_wrapper->remote->OnConnected(std::move(connection));
  connecting_sockets_.insert(std::move(sock_wrapper));
}

void ArcFlossBridge::OnConnectionStateChanged(
    ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper,
    int socket_ready_callback_id,
    floss::FlossSocketManager::ServerSocketState state,
    floss::FlossSocketManager::FlossListeningSocket socket,
    floss::FlossSocketManager::BtifStatus status) {
  if (!sock_wrapper) {
    // sock_wrapper has been disposed (or worse), nothing to do, but resolve
    // callback with failure if it is still around.
    CompleteListenSocketReady(socket_ready_callback_id,
                              mojom::BluetoothStatus::FAIL, sock_wrapper,
                              socket);
    return;
  }

  if (status != floss::FlossSocketManager::BtifStatus::kSuccess) {
    LOG(ERROR) << "Received OnConnectionStateChanged callback with "
                  "non-Success status: "
               << static_cast<int>(status);
    CompleteListenSocketReady(socket_ready_callback_id,
                              mojom::BluetoothStatus::FAIL, sock_wrapper,
                              socket);
    return;
  }

  if (state != floss::FlossSocketManager::ServerSocketState::kReady) {
    // Socket isn't ready for accepting connections, nothing to do
    return;
  }

  // At this point we may assume that listening socket creation was a
  // success. Let CompleteListenSocketReady know if it doesn't already.
  CompleteListenSocketReady(socket_ready_callback_id,
                            mojom::BluetoothStatus::SUCCESS, sock_wrapper,
                            socket);
  if (!AdapterReadyAndRegistered()) {
    return;
  }

  floss::ResponseCallback<floss::FlossDBusClient::BtifStatus>
      response_callback = base::BindOnce(&OnNoOpBtifResult);
  // TODO: figure out the correct timeout here
  floss::FlossDBusManager::Get()->GetSocketManager()->Accept(
      socket.id, /*timeout_ms=*/std::nullopt, std::move(response_callback));
}

void ArcFlossBridge::OnConnectionAccepted(
    const ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper,
    floss::FlossSocketManager::FlossSocket&& socket) {
  if (!sock_wrapper) {
    // sock_wrapper has been disposed (or worse), nothing to do
    return;
  }

  if (!socket.is_valid() || !socket.fd.has_value()) {
    LOG(ERROR) << "New socket connection was accepted with invalid socket";
    return;
  }

  mojo::ScopedHandle handle =
      mojo::WrapPlatformHandle(mojo::PlatformHandle(std::move(*socket.fd)));
  auto connection = mojom::BluetoothSocketConnection::New();
  connection->sock = std::move(handle);
  connection->addr =
      mojom::BluetoothAddress::From(socket.remote_device.address);
  connection->port = socket.port;
  switch (socket.type) {
    case floss::FlossSocketManager::SocketType::kRfcomm:
    case floss::FlossSocketManager::SocketType::kL2cap:
      sock_wrapper->remote->OnAccepted(std::move(connection));
      break;
    default:
      return;
  }
}

int ArcFlossBridge::GetPortOrChannel(
    ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper,
    floss::FlossSocketManager::FlossListeningSocket socket) {
  switch (sock_wrapper->sock_type) {
    case mojom::BluetoothSocketType::TYPE_RFCOMM:
      if (!socket.channel) {
        return 0;
      }
      return *socket.channel;
    case mojom::BluetoothSocketType::TYPE_L2CAP_LE:
      if (!socket.psm) {
        return 0;
      }
      return *socket.psm;
    default:
      return 0;
  }
}

void ArcFlossBridge::CompleteListenSocketReady(
    int socket_ready_callback_id,
    mojom::BluetoothStatus status,
    ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper) {
  CompleteListenSocketReady(socket_ready_callback_id, status,
                            /*port_or_channel*/ 0, sock_wrapper);
}

void ArcFlossBridge::CompleteListenSocketReady(
    int socket_ready_callback_id,
    mojom::BluetoothStatus status,
    int port_or_channel,
    ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper) {
  if (!socket_ready_callbacks_.contains(socket_ready_callback_id)) {
    return;
  }

  BluetoothSocketListenCallback callback =
      std::move(socket_ready_callbacks_[socket_ready_callback_id]);
  socket_ready_callbacks_.erase(socket_ready_callback_id);
  if (status != mojom::BluetoothStatus::SUCCESS) {
    std::move(callback).Run(
        mojom::BluetoothStatus::FAIL, /*port=*/0,
        mojo::PendingReceiver<mojom::BluetoothListenSocketClient>());
  } else {
    std::move(callback).Run(mojom::BluetoothStatus::SUCCESS, port_or_channel,
                            sock_wrapper->remote.BindNewPipeAndPassReceiver());
    sock_wrapper->remote.set_disconnect_handler(
        base::BindOnce(&ArcFlossBridge::CloseBluetoothListeningSocket,
                       weak_factory_.GetWeakPtr(), sock_wrapper));
  }
}

void ArcFlossBridge::CompleteListenSocketReady(
    int socket_ready_callback_id,
    mojom::BluetoothStatus status,
    ArcBluetoothBridge::BluetoothListeningSocket* sock_wrapper,
    floss::FlossSocketManager::FlossListeningSocket socket) {
  if (!socket_ready_callbacks_.contains(socket_ready_callback_id)) {
    return;
  }
  if (!listening_sockets_.contains(sock_wrapper)) {
    return;
  }
  listening_sockets_[sock_wrapper].second = socket.id;
  CompleteListenSocketReady(socket_ready_callback_id, status,
                            GetPortOrChannel(sock_wrapper, socket),
                            sock_wrapper);
}

void ArcFlossBridge::CompleteCreateSdpRecord(
    device::BluetoothUUID uuid,
    arc::mojom::BluetoothCreateSdpRecordResultPtr result) {
  if (!base::Contains(create_sdp_record_callbacks_, uuid)) {
    return;
  }

  CreateSdpRecordCallback callback =
      std::move(create_sdp_record_callbacks_[uuid]);
  create_sdp_record_callbacks_.erase(uuid);
  std::move(callback).Run(std::move(result));
}

bool ArcFlossBridge::AdapterReadyAndRegistered() {
  if (!GetAdapter() || !GetAdapter()->IsPresent()) {
    return false;
  }

  if (!floss::FlossDBusManager::Get()->GetAdapterClient()->HasObserver(this)) {
    floss::FlossDBusManager::Get()->GetAdapterClient()->AddObserver(this);
  }

  return true;
}

}  // namespace arc