File: floss_socket_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (767 lines) | stat: -rw-r--r-- 27,995 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/floss/floss_socket_manager.h"

#include "base/containers/contains.h"
#include "base/types/expected.h"

namespace floss {
namespace {
void HandleExported(const std::string& method_name,
                    const std::string& interface_name,
                    const std::string& object_path,
                    bool success) {
  DVLOG(1) << (success ? "Successfully exported " : "Failed to export ")
           << method_name << " on interface = " << interface_name
           << ", object = " << object_path;
}

constexpr char kListeningPropId[] = "id";
constexpr char kListeningPropSockType[] = "sock_type";
constexpr char kListeningPropFlags[] = "flags";
constexpr char kListeningPropPsm[] = "psm";
constexpr char kListeningPropChannel[] = "channel";
constexpr char kListeningPropName[] = "name";
constexpr char kListeningPropUuid[] = "uuid";

constexpr char kConnectingPropId[] = "id";
constexpr char kConnectingPropRemoteDevice[] = "remote_device";
constexpr char kConnectingPropSockType[] = "sock_type";
constexpr char kConnectingPropFlags[] = "flags";
constexpr char kConnectingPropFd[] = "fd";
constexpr char kConnectingPropPort[] = "port";
constexpr char kConnectingPropUuid[] = "uuid";
constexpr char kConnectingPropMaxRxSize[] = "max_rx_size";
constexpr char kConnectingPropMaxTxSize[] = "max_tx_size";

constexpr char kResultPropStatus[] = "status";
constexpr char kResultPropId[] = "id";
}  // namespace

template <>
bool FlossDBusClient::ReadDBusParam(dbus::MessageReader* reader,
                                    FlossSocketManager::SocketType* type) {
  uint32_t raw_type = 0;
  bool read = FlossDBusClient::ReadDBusParam(reader, &raw_type);

  if (read) {
    *type = static_cast<FlossSocketManager::SocketType>(raw_type);
  }

  return read;
}

template <>
void FlossDBusClient::WriteDBusParam(
    dbus::MessageWriter* writer,
    const FlossSocketManager::SocketType& type) {
  WriteDBusParam(writer, static_cast<uint32_t>(type));
}

template <>
bool FlossDBusClient::ReadDBusParam(
    dbus::MessageReader* reader,
    FlossSocketManager::FlossListeningSocket* socket) {
  dbus::MessageReader array(nullptr);
  dbus::MessageReader dict(nullptr);

  std::map<std::string, bool> required_keys = {
      {kListeningPropId, false},      {kListeningPropSockType, false},
      {kListeningPropFlags, false},   {kListeningPropPsm, false},
      {kListeningPropChannel, false}, {kListeningPropName, false},
      {kListeningPropUuid, false},
  };

  if (!reader->PopArray(&array)) {
    return false;
  }

  while (array.PopDictEntry(&dict)) {
    std::string key;
    dict.PopString(&key);

    if (base::Contains(required_keys, key)) {
      if (key == kListeningPropId) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->id);
      } else if (key == kListeningPropSockType) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->type);
      } else if (key == kListeningPropFlags) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->flags);
      } else if (key == kListeningPropPsm) {
        required_keys[key] =
            ReadDBusParamFromVariant<std::optional<int>>(&dict, &socket->psm);
      } else if (key == kListeningPropChannel) {
        required_keys[key] = ReadDBusParamFromVariant<std::optional<int>>(
            &dict, &socket->channel);
      } else if (key == kListeningPropName) {
        required_keys[key] =
            ReadDBusParamFromVariant<std::optional<std::string>>(&dict,
                                                                 &socket->name);
      } else if (key == kListeningPropUuid) {
        required_keys[key] =
            ReadDBusParamFromVariant<std::optional<device::BluetoothUUID>>(
                &dict, &socket->uuid);
      }
    }
  }

  // Make sure all required keys were correctly parsed.
  bool result = true;
  for (auto [key, found] : required_keys) {
    result = result && found;
  }

  return result;
}

template bool
FlossDBusClient::ReadDBusParam<FlossSocketManager::FlossListeningSocket>(
    dbus::MessageReader* reader,
    std::optional<FlossSocketManager::FlossListeningSocket>* socket);

template <>
void FlossDBusClient::WriteDBusParam(
    dbus::MessageWriter* writer,
    const FlossSocketManager::FlossListeningSocket& socket) {
  dbus::MessageWriter array(nullptr);
  dbus::MessageWriter dict(nullptr);

  writer->OpenArray("{sv}", &array);

  WriteDictEntry(&array, kListeningPropId, socket.id);
  WriteDictEntry(&array, kListeningPropSockType, socket.type);
  WriteDictEntry(&array, kListeningPropFlags, socket.flags);
  WriteDictEntry(&array, kListeningPropPsm, socket.psm);
  WriteDictEntry(&array, kListeningPropChannel, socket.channel);
  WriteDictEntry(&array, kListeningPropName, socket.name);
  WriteDictEntry(&array, kListeningPropUuid, socket.uuid);

  writer->CloseContainer(&array);
}

template <>
bool FlossDBusClient::ReadDBusParam(dbus::MessageReader* reader,
                                    FlossSocketManager::FlossSocket* socket) {
  dbus::MessageReader array(nullptr);
  dbus::MessageReader dict(nullptr);
  std::map<std::string, bool> required_keys = {
      {kConnectingPropId, false},        {kConnectingPropRemoteDevice, false},
      {kConnectingPropSockType, false},  {kConnectingPropFlags, false},
      {kConnectingPropFd, false},        {kConnectingPropPort, false},
      {kConnectingPropUuid, false},      {kConnectingPropMaxRxSize, false},
      {kConnectingPropMaxTxSize, false},
  };
  if (!reader->PopArray(&array)) {
    return false;
  }

  while (array.PopDictEntry(&dict)) {
    std::string key;
    dict.PopString(&key);

    if (base::Contains(required_keys, key)) {
      if (key == kConnectingPropId) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->id);
      } else if (key == kConnectingPropRemoteDevice) {
        required_keys[key] =
            ReadDBusParamFromVariant(&dict, &socket->remote_device);
      } else if (key == kConnectingPropSockType) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->type);
      } else if (key == kConnectingPropFlags) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->flags);
      } else if (key == kConnectingPropFd) {
        required_keys[key] =
            ReadDBusParamFromVariant<std::optional<base::ScopedFD>>(
                &dict, &socket->fd);
      } else if (key == kConnectingPropPort) {
        required_keys[key] = ReadDBusParamFromVariant(&dict, &socket->port);
      } else if (key == kConnectingPropUuid) {
        required_keys[key] =
            ReadDBusParamFromVariant<std::optional<device::BluetoothUUID>>(
                &dict, &socket->uuid);
      } else if (key == kConnectingPropMaxRxSize) {
        required_keys[key] =
            ReadDBusParamFromVariant(&dict, &socket->max_rx_size);
      } else if (key == kConnectingPropMaxTxSize) {
        required_keys[key] =
            ReadDBusParamFromVariant(&dict, &socket->max_tx_size);
      }
    }
  }

  // Make sure all required keys were correctly parsed.
  bool result = true;
  for (auto [key, found] : required_keys) {
    result = result && found;
  }

  return result;
}

template bool FlossDBusClient::ReadDBusParam<FlossSocketManager::FlossSocket>(
    dbus::MessageReader* reader,
    std::optional<FlossSocketManager::FlossSocket>* socket);

template <>
void FlossDBusClient::WriteDBusParam(
    dbus::MessageWriter* writer,
    const FlossSocketManager::FlossSocket& socket) {
  dbus::MessageWriter array(nullptr);
  dbus::MessageWriter dict(nullptr);

  writer->OpenArray("{sv}", &array);

  WriteDictEntry(&array, kConnectingPropId, socket.id);
  WriteDictEntry(&array, kConnectingPropRemoteDevice, socket.remote_device);
  WriteDictEntry(&array, kConnectingPropSockType, socket.type);
  WriteDictEntry(&array, kConnectingPropFlags, socket.flags);
  WriteDictEntry(&array, kConnectingPropFd, socket.fd);
  WriteDictEntry(&array, kConnectingPropPort, socket.port);
  WriteDictEntry(&array, kConnectingPropUuid, socket.uuid);
  WriteDictEntry(&array, kConnectingPropMaxRxSize, socket.max_rx_size);
  WriteDictEntry(&array, kConnectingPropMaxTxSize, socket.max_tx_size);

  writer->CloseContainer(&array);
}

template <>
bool FlossDBusClient::ReadDBusParam(
    dbus::MessageReader* reader,
    FlossSocketManager::SocketResult* socket_result) {
  dbus::MessageReader array(nullptr);
  dbus::MessageReader dict(nullptr);

  std::map<std::string, bool> required_keys = {
      {kResultPropStatus, false},
      {kResultPropId, false},
  };

  if (!reader->PopArray(&array)) {
    return false;
  }

  while (array.PopDictEntry(&dict)) {
    std::string key;
    dict.PopString(&key);

    if (base::Contains(required_keys, key)) {
      if (key == kResultPropStatus) {
        required_keys[key] =
            ReadDBusParamFromVariant(&dict, &socket_result->status);
      } else if (key == kResultPropId) {
        required_keys[key] =
            ReadDBusParamFromVariant(&dict, &socket_result->id);
      }
    }
  }

  // Make sure all required keys were correctly parsed.
  bool result = true;
  for (auto [key, found] : required_keys) {
    result = result && found;
  }

  return result;
}

template <>
void FlossDBusClient::WriteDBusParam(
    dbus::MessageWriter* writer,
    const FlossSocketManager::SocketResult& socket_result) {
  dbus::MessageWriter array(nullptr);
  dbus::MessageWriter dict(nullptr);

  writer->OpenArray("{sv}", &array);

  WriteDictEntry(&array, kResultPropStatus,
                 static_cast<uint32_t>(socket_result.status));
  WriteDictEntry(&array, kResultPropId, socket_result.id);

  writer->CloseContainer(&array);
}

template <>
const DBusTypeInfo& GetDBusTypeInfo(const FlossSocketManager::SocketType*) {
  static DBusTypeInfo info{"u", "SocketType"};
  return info;
}

template <>
const DBusTypeInfo& GetDBusTypeInfo(const FlossSocketManager::FlossSocket*) {
  static DBusTypeInfo info{"a{sv}", "FlossSocket"};
  return info;
}

int FlossSocketManager::GetRawFlossFlagsFromBluetoothFlags(bool encrypt,
                                                           bool auth,
                                                           bool auth_mitm,
                                                           bool auth_16_digit,
                                                           bool no_sdp) {
  int flags = 0;
  return flags |
         (encrypt ? static_cast<int>(SocketFlags::kSocketFlagsEncrypt) : 0) |
         (auth ? static_cast<int>(SocketFlags::kSocketFlagsAuth) : 0) |
         (auth_mitm ? static_cast<int>(SocketFlags::kSocketFlagsAuthMitm) : 0) |
         (auth_16_digit ? static_cast<int>(SocketFlags::kSocketFlagsAuth16Digit)
                        : 0) |
         (no_sdp ? static_cast<int>(SocketFlags::kSocketFlagsNoSdp) : 0);
}

FlossSocketManager::FlossListeningSocket::FlossListeningSocket() = default;
FlossSocketManager::FlossListeningSocket::FlossListeningSocket(
    const FlossListeningSocket&) = default;
FlossSocketManager::FlossListeningSocket::~FlossListeningSocket() = default;

FlossSocketManager::FlossSocket::FlossSocket() = default;
FlossSocketManager::FlossSocket::FlossSocket(FlossSocket&&) = default;
FlossSocketManager::FlossSocket::~FlossSocket() = default;

// static
const char FlossSocketManager::kErrorInvalidCallback[] =
    "org.chromium.Error.InvalidCallbackId";

// static
const char FlossSocketManager::kExportedCallbacksPath[] =
    "/org/chromium/bluetooth/socket_manager/callback";

// static
std::unique_ptr<FlossSocketManager> FlossSocketManager::Create() {
  return std::make_unique<FlossSocketManager>();
}

FlossSocketManager::FlossSocketManager() = default;

FlossSocketManager::~FlossSocketManager() {
  if (callback_id_ != kInvalidCallbackId) {
    CallSocketMethod(
        base::BindOnce(&FlossSocketManager::CompleteUnregisterCallback,
                       weak_ptr_factory_.GetWeakPtr()),
        socket_manager::kUnregisterCallback, callback_id_);
  }
  if (bus_) {
    bus_->UnregisterExportedObject(dbus::ObjectPath(kExportedCallbacksPath));
  }
}

void FlossSocketManager::ListenUsingL2cap(
    const Security security_level,
    ResponseCallback<BtifStatus> callback,
    ConnectionStateChanged ready_cb,
    ConnectionAccepted new_connection_cb) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(base::unexpected(Error(kErrorInvalidCallback, "")));
    return;
  }

  const char* method = security_level == Security::kInsecure
                           ? socket_manager::kListenUsingInsecureL2capChannel
                           : socket_manager::kListenUsingL2capChannel;

  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteListen,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(ready_cb), std::move(new_connection_cb)),
      method, callback_id_);
}

void FlossSocketManager::ListenUsingL2capLe(
    const Security security_level,
    ResponseCallback<BtifStatus> callback,
    ConnectionStateChanged ready_cb,
    ConnectionAccepted new_connection_cb) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(base::unexpected(Error(kErrorInvalidCallback, "")));
    return;
  }

  const char* method = security_level == Security::kInsecure
                           ? socket_manager::kListenUsingInsecureL2capLeChannel
                           : socket_manager::kListenUsingL2capLeChannel;

  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteListen,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(ready_cb), std::move(new_connection_cb)),
      method, callback_id_);
}

void FlossSocketManager::ListenUsingRfcommAlt(
    const std::optional<std::string> name,
    const std::optional<device::BluetoothUUID> application_uuid,
    const std::optional<int> channel,
    const std::optional<int> flags,
    ResponseCallback<BtifStatus> callback,
    ConnectionStateChanged ready_cb,
    ConnectionAccepted new_connection_cb) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(
        base::unexpected(Error(kErrorInvalidCallback, /*message=*/"")));
    return;
  }
  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteListen,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(ready_cb), std::move(new_connection_cb)),
      socket_manager::kListenUsingRfcomm, callback_id_, channel,
      application_uuid, name, flags);
}

void FlossSocketManager::ListenUsingRfcomm(
    const std::string& name,
    const device::BluetoothUUID& uuid,
    const Security security_level,
    ResponseCallback<BtifStatus> callback,
    ConnectionStateChanged ready_cb,
    ConnectionAccepted new_connection_cb) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(
        base::unexpected(Error(kErrorInvalidCallback, /*message=*/"")));
    return;
  }

  const char* method =
      security_level == Security::kInsecure
          ? socket_manager::kListenUsingInsecureRfcommWithServiceRecord
          : socket_manager::kListenUsingRfcommWithServiceRecord;
  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteListen,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(ready_cb), std::move(new_connection_cb)),
      method, callback_id_, name, uuid);
}

void FlossSocketManager::ConnectUsingL2cap(const FlossDeviceId& remote_device,
                                           const int psm,
                                           const Security security_level,
                                           ConnectionCompleted callback) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(BtifStatus::kFail, /*socket=*/std::nullopt);
    return;
  }

  const char* method = security_level == Security::kInsecure
                           ? socket_manager::kCreateInsecureL2capChannel
                           : socket_manager::kCreateL2capChannel;

  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteConnect,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)),
      method, callback_id_, remote_device, psm);
}

void FlossSocketManager::ConnectUsingL2capLe(const FlossDeviceId& remote_device,
                                             const int psm,
                                             const Security security_level,
                                             ConnectionCompleted callback) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(BtifStatus::kFail, /*socket=*/std::nullopt);
    return;
  }

  const char* method = security_level == Security::kInsecure
                           ? socket_manager::kCreateInsecureL2capLeChannel
                           : socket_manager::kCreateL2capLeChannel;

  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteConnect,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)),
      method, callback_id_, remote_device, psm);
}

void FlossSocketManager::ConnectUsingRfcomm(const FlossDeviceId& remote_device,
                                            const device::BluetoothUUID& uuid,
                                            const Security security_level,
                                            ConnectionCompleted callback) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(BtifStatus::kFail, /*socket=*/std::nullopt);
    return;
  }

  const char* method =
      security_level == Security::kInsecure
          ? socket_manager::kCreateInsecureRfcommSocketToServiceRecord
          : socket_manager::kCreateRfcommSocketToServiceRecord;

  CallSocketMethod(
      base::BindOnce(&FlossSocketManager::CompleteConnect,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)),
      method, callback_id_, remote_device, uuid);
}

void FlossSocketManager::Accept(const SocketId id,
                                std::optional<uint32_t> timeout_ms,
                                ResponseCallback<BtifStatus> callback) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(base::unexpected(Error(kErrorInvalidCallback, "")));
    return;
  }

  CallSocketMethod(std::move(callback), socket_manager::kAccept, callback_id_,
                   id, timeout_ms);
}

void FlossSocketManager::Close(const SocketId id,
                               ResponseCallback<BtifStatus> callback) {
  if (callback_id_ == kInvalidCallbackId) {
    std::move(callback).Run(base::unexpected(Error(kErrorInvalidCallback, "")));
    return;
  }

  CallSocketMethod(std::move(callback), socket_manager::kClose, callback_id_,
                   id);
}

void FlossSocketManager::Init(dbus::Bus* bus,
                              const std::string& service_name,
                              const int adapter_index,
                              base::Version version,
                              base::OnceClosure on_ready) {
  bus_ = bus;
  service_name_ = service_name;
  adapter_path_ = GenerateAdapterPath(adapter_index);
  version_ = version;

  dbus::ObjectProxy* object_proxy =
      bus_->GetObjectProxy(service_name_, adapter_path_);
  if (!object_proxy) {
    LOG(ERROR) << "FlossSocketManager couldn't init. Object proxy was null.";
    return;
  }

  dbus::ExportedObject* callbacks =
      bus_->GetExportedObject(dbus::ObjectPath(kExportedCallbacksPath));
  if (!callbacks) {
    LOG(ERROR) << "FlossSocketManager couldn't export client callbacks.";
    return;
  }

  // Export callbacks for socket manager.
  callbacks->ExportMethod(
      socket_manager::kCallbackInterface,
      socket_manager::kOnIncomingSocketReady,
      base::BindRepeating(&FlossSocketManager::OnIncomingSocketReady,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&HandleExported, socket_manager::kOnIncomingSocketReady));
  callbacks->ExportMethod(
      socket_manager::kCallbackInterface,
      socket_manager::kOnIncomingSocketClosed,
      base::BindRepeating(&FlossSocketManager::OnIncomingSocketClosed,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&HandleExported, socket_manager::kOnIncomingSocketClosed));
  callbacks->ExportMethod(
      socket_manager::kCallbackInterface,
      socket_manager::kOnHandleIncomingConnection,
      base::BindRepeating(&FlossSocketManager::OnHandleIncomingConnection,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&HandleExported,
                     socket_manager::kOnHandleIncomingConnection));
  callbacks->ExportMethod(
      socket_manager::kCallbackInterface,
      socket_manager::kOnOutgoingConnectionResult,
      base::BindRepeating(&FlossSocketManager::OnOutgoingConnectionResult,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindOnce(&HandleExported,
                     socket_manager::kOnOutgoingConnectionResult));

  // Register callbacks and store the callback id.
  dbus::MethodCall register_callback(kSocketManagerInterface,
                                     socket_manager::kRegisterCallback);
  dbus::MessageWriter writer(&register_callback);
  writer.AppendObjectPath(dbus::ObjectPath(kExportedCallbacksPath));

  object_proxy->CallMethodWithErrorResponse(
      &register_callback, kDBusTimeoutMs,
      base::BindOnce(&FlossSocketManager::CompleteRegisterCallback,
                     weak_ptr_factory_.GetWeakPtr()));

  on_ready_ = std::move(on_ready);
}

void FlossSocketManager::CompleteRegisterCallback(
    dbus::Response* response,
    dbus::ErrorResponse* error_response) {
  if (error_response) {
    FlossDBusClient::LogErrorResponse("SocketManager::RegisterCallback",
                                      error_response);
  } else {
    dbus::MessageReader reader(response);
    uint32_t result;
    if (!reader.PopUint32(&result)) {
      LOG(ERROR)
          << "No callback id provided for SocketManager::RegisterCallback";
      return;
    }

    callback_id_ = result;

    if (on_ready_) {
      std::move(on_ready_).Run();
    }
  }
}

void FlossSocketManager::CompleteUnregisterCallback(DBusResult<bool> result) {
  if (!result.has_value() || *result == false) {
    LOG(WARNING) << __func__ << ": Failed to unregister callback";
  }
}

void FlossSocketManager::CompleteListen(ResponseCallback<BtifStatus> callback,
                                        ConnectionStateChanged ready_cb,
                                        ConnectionAccepted new_connection_cb,
                                        DBusResult<SocketResult> result) {
  if (!result.has_value()) {
    std::move(callback).Run(base::unexpected(result.error()));
    return;
  }

  // We got back a valid socket id from listen. Put into listening list.
  if (result->id != kInvalidSocketId) {
    listening_sockets_to_callbacks_.insert({
        result->id,
        {std::move(ready_cb), std::move(new_connection_cb)},
    });
  }

  // Complete callback with the BtifStatus.
  std::move(callback).Run(result->status);
}

void FlossSocketManager::CompleteConnect(ConnectionCompleted callback,
                                         DBusResult<SocketResult> result) {
  if (!result.has_value()) {
    std::move(callback).Run(BtifStatus::kFail, /*socket=*/std::nullopt);
    return;
  }

  // If we got back a valid socket id from connect, put into connecting list.
  // Otherwise, return the failed status back upwards.
  if (result->id != kInvalidSocketId) {
    connecting_sockets_to_callbacks_.insert({
        result->id,
        std::move(callback),
    });
  } else {
    std::move(callback).Run(result->status, /*socket=*/std::nullopt);
  }
}

void FlossSocketManager::OnIncomingSocketReady(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);
  FlossListeningSocket socket;
  BtifStatus status;

  if (!ReadAllDBusParams(&reader, &socket, &status)) {
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, kErrorInvalidParameters, std::string()));
    return;
  }

  // If this is a known socket, run the |ConnectionStateChanged| callback.
  auto found = listening_sockets_to_callbacks_.find(socket.id);
  if (found != listening_sockets_to_callbacks_.end()) {
    auto& [key, callbacks] = *found;
    auto& [state_changed, accepted] = callbacks;

    state_changed.Run(ServerSocketState::kReady, socket, status);
  }

  std::move(response_sender).Run(dbus::Response::FromMethodCall(method_call));
}

void FlossSocketManager::OnIncomingSocketClosed(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);
  SocketId id;
  BtifStatus status;

  if (!ReadAllDBusParams(&reader, &id, &status)) {
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, kErrorInvalidParameters, std::string()));
    return;
  }

  // If this is a known socket, run the |ConnectionStateChanged| callback and
  // remove this from the list of listening sockets.
  auto found = listening_sockets_to_callbacks_.find(id);
  if (found != listening_sockets_to_callbacks_.end()) {
    FlossListeningSocket socket;
    socket.id = id;

    auto& [key, callbacks] = *found;
    auto& [state_changed, accepted] = callbacks;

    state_changed.Run(ServerSocketState::kClosed, socket, status);
    listening_sockets_to_callbacks_.erase(found);
  }

  std::move(response_sender).Run(dbus::Response::FromMethodCall(method_call));
}

void FlossSocketManager::OnHandleIncomingConnection(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);
  SocketId id;
  FlossSocket socket;

  if (!ReadAllDBusParams(&reader, &id, &socket)) {
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, kErrorInvalidParameters, std::string()));
    return;
  }

  // New connection on a known listening socket. Call the |ConnectionAccepted|
  // callback.
  auto found = listening_sockets_to_callbacks_.find(id);
  if (found != listening_sockets_to_callbacks_.end()) {
    auto& [key, callbacks] = *found;
    auto& [state_changed, accepted] = callbacks;

    accepted.Run(std::move(socket));
  }

  std::move(response_sender).Run(dbus::Response::FromMethodCall(method_call));
}

void FlossSocketManager::OnOutgoingConnectionResult(
    dbus::MethodCall* method_call,
    dbus::ExportedObject::ResponseSender response_sender) {
  dbus::MessageReader reader(method_call);
  SocketId id;
  BtifStatus status;
  std::optional<FlossSocket> socket;

  if (!ReadAllDBusParams(&reader, &id, &status, &socket)) {
    std::move(response_sender)
        .Run(dbus::ErrorResponse::FromMethodCall(
            method_call, kErrorInvalidParameters, std::string()));
    return;
  }

  // Connecting callback finished. Call the |ConnectionCompleted| callback and
  // remove this entry from the pending connections list.
  auto found = connecting_sockets_to_callbacks_.find(id);
  if (found != connecting_sockets_to_callbacks_.end()) {
    auto& [key, complete_callback] = *found;
    std::move(complete_callback).Run(status, std::move(socket));
    connecting_sockets_to_callbacks_.erase(found);
  }

  std::move(response_sender).Run(dbus::Response::FromMethodCall(method_call));
}

// Specializations for default responses.
template void FlossDBusClient::DefaultResponseWithCallback(
    ResponseCallback<FlossSocketManager::SocketResult> callback,
    dbus::Response* response,
    dbus::ErrorResponse* error_response);

}  // namespace floss