File: session_manager_client.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; 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,806; 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 (1257 lines) | stat: -rw-r--r-- 51,069 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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "chromeos/ash/components/dbus/session_manager/session_manager_client.h"

#include <stddef.h>
#include <stdint.h>

#include <cstring>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>

#include "base/containers/span.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/platform_shared_memory_region.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/read_only_shared_memory_region.h"
#include "base/memory/writable_shared_memory_region.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/unguessable_token.h"
#include "chromeos/ash/components/dbus/arc/arc.pb.h"
#include "chromeos/ash/components/dbus/cryptohome/rpc.pb.h"
#include "chromeos/ash/components/dbus/login_manager/login_screen_storage.pb.h"
#include "chromeos/ash/components/dbus/login_manager/policy_descriptor.pb.h"
#include "chromeos/ash/components/dbus/session_manager/fake_session_manager_client.h"
#include "chromeos/ash/components/dbus/session_manager/policy_descriptor.h"
#include "chromeos/dbus/common/blocking_method_caller.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "dbus/bus.h"
#include "dbus/error.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/login_manager/dbus-constants.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace ash {

namespace {

SessionManagerClient* g_instance = nullptr;

using RetrievePolicyResponseType =
    SessionManagerClient::RetrievePolicyResponseType;

constexpr char kEmptyAccountId[] = "";
// The timeout used when starting the android container is 90 seconds
constexpr int kStartArcTimeout = 90 * 1000;

// TODO(b/205032502): Because upgrading the container from mini to full often
// takes more than 25 seconds, increasing it to 1 minute for now. Once we have
// the update metrics, update the timeout to a tighter value.
constexpr int kUpgradeTimeoutMs = 60 * 1000;  // 60 seconds

// 10MB. It's the current restriction enforced by session manager.
const size_t kSharedMemoryDataSizeLimit = 10 * 1024 * 1024;

// Copy of values from login_manager::SessionManagerImpl.
// TODO(crbug.com/40071048): Move to system_api/dbus/service_constants.h
constexpr char kStopping[] = "stopping";

// Helper to get the enum type of RetrievePolicyResponseType based on error
// name.
RetrievePolicyResponseType GetPolicyResponseTypeByError(
    std::string_view error_name) {
  if (error_name == login_manager::dbus_error::kNone) {
    return RetrievePolicyResponseType::SUCCESS;
  } else if (error_name == login_manager::dbus_error::kGetServiceFail ||
             error_name == login_manager::dbus_error::kSessionDoesNotExist) {
    // TODO(crbug.com/41344863): Remove kSessionDoesNotExist case once Chrome OS
    // has switched to kGetServiceFail.
    return RetrievePolicyResponseType::GET_SERVICE_FAIL;
  } else if (error_name == login_manager::dbus_error::kSigEncodeFail) {
    return RetrievePolicyResponseType::POLICY_ENCODE_ERROR;
  }
  return RetrievePolicyResponseType::OTHER_ERROR;
}

// Creates a pipe that contains the given data. The data will be prefixed by a
// size_t sized variable containing the size of the data to read. Since we don't
// pass this pipe's read end anywhere, we can be sure that the only FD that can
// read from that pipe will be closed on browser's exit, therefore the password
// won't be leaked if the browser crashes.
base::ScopedFD CreatePasswordPipe(const std::string& data) {
  // 64k of data, minus 64 bits for a preceding size. This number was chosen to
  // fit all the data in a single pipe buffer and avoid blocking on write.
  // (http://man7.org/linux/man-pages/man7/pipe.7.html)
  const size_t kPipeDataSizeLimit = 1024 * 64 - sizeof(size_t);

  int pipe_fds[2];
  if (data.size() > kPipeDataSizeLimit ||
      !base::CreateLocalNonBlockingPipe(pipe_fds)) {
    DLOG(ERROR) << "Failed to create pipe";
    return base::ScopedFD();
  }
  base::ScopedFD pipe_read_end(pipe_fds[0]);
  base::ScopedFD pipe_write_end(pipe_fds[1]);

  const size_t data_size = data.size();

  base::WriteFileDescriptor(pipe_write_end.get(),
                            base::byte_span_from_ref(data_size));
  base::WriteFileDescriptor(pipe_write_end.get(), data);

  return pipe_read_end;
}

// Creates a read-only shared memory region that contains the given data.
base::ScopedFD CreateSharedMemoryRegionFDWithData(const std::string& data) {
  if (data.size() > kSharedMemoryDataSizeLimit) {
    LOG(ERROR) << "Couldn't create shared memory, data is too big.";
    return base::ScopedFD();
  }
  auto region = base::WritableSharedMemoryRegion::Create(data.size());
  base::WritableSharedMemoryMapping mapping = region.Map();
  if (!mapping.IsValid())
    return base::ScopedFD();
  mapping.GetMemoryAsSpan<uint8_t>().copy_from(base::as_byte_span(data));
  return base::WritableSharedMemoryRegion::TakeHandleForSerialization(
             std::move(region))
      .PassPlatformHandle()
      .readonly_fd;
}

// Reads |secret_size| bytes from a given shared memory region. Puts result into
// |secret|. |fd| should point at a read-only shared memory region.
bool ReadSecretFromSharedMemory(base::ScopedFD fd,
                                size_t secret_size,
                                std::vector<uint8_t>* secret) {
  if (secret_size > kSharedMemoryDataSizeLimit) {
    LOG(ERROR) << "Couldn't read secret from the shared memory, "
                  "secret's size is too big.";
    return false;
  }
  auto platform_region(base::subtle::PlatformSharedMemoryRegion::Take(
      std::move(fd), base::subtle::PlatformSharedMemoryRegion::Mode::kReadOnly,
      secret_size, base::UnguessableToken::Create()));
  if (!platform_region.IsValid())
    return false;
  auto region =
      base::ReadOnlySharedMemoryRegion::Deserialize(std::move(platform_region));
  if (!region.IsValid())
    return false;
  base::ReadOnlySharedMemoryMapping mapping = region.Map();
  if (!mapping.IsValid())
    return false;
  secret->resize(secret_size);
  memcpy(secret->data(), mapping.memory(), secret->size());
  return true;
}

}  // namespace

// The SessionManagerClient implementation used in production.
class SessionManagerClientImpl : public SessionManagerClient {
 public:
  SessionManagerClientImpl() = default;

  SessionManagerClientImpl(const SessionManagerClientImpl&) = delete;
  SessionManagerClientImpl& operator=(const SessionManagerClientImpl&) = delete;

  ~SessionManagerClientImpl() override = default;

  // SessionManagerClient overrides:
  void SetStubDelegate(StubDelegate* delegate) override {
    // Do nothing; this isn't a stub implementation.
  }

  void AddObserver(Observer* observer) override {
    observers_.AddObserver(observer);
  }

  void RemoveObserver(Observer* observer) override {
    observers_.RemoveObserver(observer);
  }

  bool HasObserver(const Observer* observer) const override {
    return observers_.HasObserver(observer);
  }

  void WaitForServiceToBeAvailable(
      chromeos::WaitForServiceToBeAvailableCallback callback) override {
    session_manager_proxy_->WaitForServiceToBeAvailable(std::move(callback));
  }

  bool IsScreenLocked() const override { return screen_is_locked_; }

  void EmitLoginPromptVisible() override {
    SimpleMethodCallToSessionManager(
        login_manager::kSessionManagerEmitLoginPromptVisible);
    for (auto& observer : observers_)
      observer.EmitLoginPromptVisibleCalled();
  }

  void EmitAshInitialized() override {
    SimpleMethodCallToSessionManager(
        login_manager::kSessionManagerEmitAshInitialized);
  }

  void RestartJob(int socket_fd,
                  const std::vector<std::string>& argv,
                  RestartJobReason reason,
                  chromeos::VoidDBusMethodCallback callback) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerRestartJob);
    dbus::MessageWriter writer(&method_call);
    writer.AppendFileDescriptor(socket_fd);
    writer.AppendArrayOfStrings(argv);
    writer.AppendUint32(static_cast<uint32_t>(reason));
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void SaveLoginPassword(const std::string& password) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerSaveLoginPassword);
    dbus::MessageWriter writer(&method_call);

    base::ScopedFD fd = CreatePasswordPipe(password);
    if (fd.get() == -1) {
      LOG(WARNING) << "Could not create password pipe.";
      return;
    }

    writer.AppendFileDescriptor(fd.get());

    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void LoginScreenStorageStore(
      const std::string& key,
      const login_manager::LoginScreenStorageMetadata& metadata,
      const std::string& data,
      LoginScreenStorageStoreCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerLoginScreenStorageStore);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(key);

    const std::string metadata_blob = metadata.SerializeAsString();
    writer.AppendArrayOfBytes(base::as_byte_span(metadata_blob));
    writer.AppendUint64(data.size());

    base::ScopedFD fd = CreateSharedMemoryRegionFDWithData(data);
    if (!fd.is_valid()) {
      std::string error = "Could not create shared memory.";
      std::move(callback).Run(std::move(error));
      return;
    }
    writer.AppendFileDescriptor(fd.get());

    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnLoginScreenStorageStore,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void LoginScreenStorageRetrieve(
      const std::string& key,
      LoginScreenStorageRetrieveCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerLoginScreenStorageRetrieve);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(key);
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnLoginScreenStorageRetrieve,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void LoginScreenStorageListKeys(
      LoginScreenStorageListKeysCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerLoginScreenStorageListKeys);
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnLoginScreenStorageListKeys,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void LoginScreenStorageDelete(const std::string& key) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerLoginScreenStorageDelete);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(key);
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void StartSession(
      const cryptohome::AccountIdentifier& cryptohome_id) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerStartSession);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    writer.AppendString("");  // Unique ID is deprecated
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void StartSessionEx(const cryptohome::AccountIdentifier& cryptohome_id,
                      bool chrome_side_key_generation) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerStartSessionEx);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    writer.AppendString("");  // Unique ID is deprecated
    writer.AppendBool(chrome_side_key_generation);
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());

    for (auto& observer : observers_) {
      observer.StartSessionExCalled();
    }
  }

  void EmitStartedUserSession(
      const cryptohome::AccountIdentifier& cryptohome_id) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerEmitStartedUserSession);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void StopSession(login_manager::SessionStopReason reason) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerStopSessionWithReason);
    dbus::MessageWriter writer(&method_call);
    writer.AppendUint32(static_cast<uint32_t>(reason));
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void LoadShillProfile(
      const cryptohome::AccountIdentifier& cryptohome_id) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerLoadShillProfile);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void StartDeviceWipe(chromeos::VoidDBusMethodCallback callback) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerStartDeviceWipe);
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
    for (auto& observer : observers_) {
      observer.PowerwashRequested(/*admin_requested*/ false);
    }
  }

  void StartRemoteDeviceWipe(
      const enterprise_management::SignedData& signed_command) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerStartRemoteDeviceWipe);
    dbus::MessageWriter writer(&method_call);
    writer.AppendProtoAsArrayOfBytes(signed_command);
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
    for (auto& observer : observers_) {
      observer.PowerwashRequested(/*admin_requested*/ true);
    }
  }

  void ClearBlockDevmodeVpd(
      chromeos::VoidDBusMethodCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerClearBlockDevmodeVpd);
    dbus::MessageWriter writer(&method_call);
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void StartTPMFirmwareUpdate(const std::string& update_mode) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerStartTPMFirmwareUpdate);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(update_mode);
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void RequestLockScreen() override {
    SimpleMethodCallToSessionManager(login_manager::kSessionManagerLockScreen);
  }

  void NotifyLockScreenShown() override {
    SimpleMethodCallToSessionManager(
        login_manager::kSessionManagerHandleLockScreenShown);
  }

  void NotifyLockScreenDismissed() override {
    SimpleMethodCallToSessionManager(
        login_manager::kSessionManagerHandleLockScreenDismissed);
  }

  bool BlockingRequestBrowserDataMigration(
      const cryptohome::AccountIdentifier& cryptohome_id,
      const std::string& mode) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerStartBrowserDataMigration);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    writer.AppendString(mode);
    auto result = blocking_method_caller_->CallMethodAndBlock(&method_call);
    if (!result.has_value()) {
      LOG(ERROR) << "BlockingRequestBrowserDataMigration failed :"
                 << result.error().name() << ":" << result.error().message();
      return false;
    }

    return true;
  }

  bool BlockingRequestBrowserDataBackwardMigration(
      const cryptohome::AccountIdentifier& cryptohome_id) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerStartBrowserDataBackwardMigration);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    auto result = blocking_method_caller_->CallMethodAndBlock(&method_call);
    if (!result.has_value()) {
      LOG(ERROR) << "BlockingRequestBrowserDataBackwardMigration failed :"
                 << result.error().name() << ":" << result.error().message();
      return false;
    }

    return true;
  }

  void RetrieveActiveSessions(ActiveSessionsCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerRetrieveActiveSessions);

    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnRetrieveActiveSessions,
                       weak_ptr_factory_.GetWeakPtr(),
                       login_manager::kSessionManagerRetrieveActiveSessions,
                       std::move(callback)));
  }

  void RetrievePolicy(const login_manager::PolicyDescriptor& descriptor,
                      RetrievePolicyCallback callback) override {
    CallRetrievePolicy(descriptor, std::move(callback));
  }

  RetrievePolicyResponseType BlockingRetrievePolicy(
      const login_manager::PolicyDescriptor& descriptor,
      std::string* policy_out) override {
    return CallBlockingRetrievePolicy(descriptor, policy_out);
  }

  void StoreDevicePolicy(const std::string& policy_blob,
                         chromeos::VoidDBusMethodCallback callback) override {
    login_manager::PolicyDescriptor descriptor =
        ash::MakeChromePolicyDescriptor(login_manager::ACCOUNT_TYPE_DEVICE,
                                        kEmptyAccountId);
    CallStorePolicy(descriptor, policy_blob, std::move(callback));
  }

  void StorePolicyForUser(const cryptohome::AccountIdentifier& cryptohome_id,
                          const std::string& policy_blob,
                          chromeos::VoidDBusMethodCallback callback) override {
    login_manager::PolicyDescriptor descriptor =
        ash::MakeChromePolicyDescriptor(login_manager::ACCOUNT_TYPE_USER,
                                        cryptohome_id.account_id());
    CallStorePolicy(descriptor, policy_blob, std::move(callback));
  }

  void StoreDeviceLocalAccountPolicy(
      const std::string& account_name,
      const std::string& policy_blob,
      chromeos::VoidDBusMethodCallback callback) override {
    login_manager::PolicyDescriptor descriptor =
        ash::MakeChromePolicyDescriptor(
            login_manager::ACCOUNT_TYPE_DEVICE_LOCAL_ACCOUNT, account_name);
    CallStorePolicy(descriptor, policy_blob, std::move(callback));
  }

  void StorePolicy(const login_manager::PolicyDescriptor& descriptor,
                   const std::string& policy_blob,
                   chromeos::VoidDBusMethodCallback callback) override {
    CallStorePolicy(descriptor, policy_blob, std::move(callback));
  }

  bool SupportsBrowserRestart() const override { return true; }

  void SetFlagsForUser(const cryptohome::AccountIdentifier& cryptohome_id,
                       const std::vector<std::string>& flags) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerSetFlagsForUser);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    writer.AppendArrayOfStrings(flags);
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void SetFeatureFlagsForUser(
      const cryptohome::AccountIdentifier& cryptohome_id,
      const std::vector<std::string>& feature_flags,
      const std::map<std::string, std::string>& origin_list_flags) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerSetFeatureFlagsForUser);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    writer.AppendArrayOfStrings(feature_flags);

    dbus::MessageWriter dict_writer(nullptr);
    writer.OpenArray("{ss}", &dict_writer);
    for (const auto& origin_entry : origin_list_flags) {
      dbus::MessageWriter entry_writer(nullptr);
      dict_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(origin_entry.first);
      entry_writer.AppendString(origin_entry.second);
      dict_writer.CloseContainer(&entry_writer);
    }
    writer.CloseContainer(&dict_writer);

    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  void GetServerBackedStateKeys(StateKeysCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerGetServerBackedStateKeys);

    // Long timeout needed because the state keys are not generated as long
    // as the time sync hasn't been done (which requires network).
    session_manager_proxy_->CallMethodWithErrorResponse(
        &method_call, dbus::ObjectProxy::TIMEOUT_MAX,
        base::BindOnce(&SessionManagerClientImpl::OnGetServerBackedStateKeys,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void GetPsmDeviceActiveSecret(
      PsmDeviceActiveSecretCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerGetPsmDeviceActiveSecret);

    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnGetPsmDeviceActiveSecret,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void StartArcMiniContainer(
      const arc::StartArcMiniInstanceRequest& request,
      chromeos::VoidDBusMethodCallback callback) override {
    DCHECK(!callback.is_null());
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerStartArcMiniContainer);
    dbus::MessageWriter writer(&method_call);

    writer.AppendProtoAsArrayOfBytes(request);

    session_manager_proxy_->CallMethod(
        &method_call, kStartArcTimeout,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void UpgradeArcContainer(const arc::UpgradeArcContainerRequest& request,
                           chromeos::VoidDBusMethodCallback callback) override {
    DCHECK(!callback.is_null());
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerUpgradeArcContainer);
    dbus::MessageWriter writer(&method_call);

    writer.AppendProtoAsArrayOfBytes(request);

    session_manager_proxy_->CallMethod(
        &method_call, kUpgradeTimeoutMs,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void StopArcInstance(const std::string& account_id,
                       bool should_backup_log,
                       chromeos::VoidDBusMethodCallback callback) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerStopArcInstance);

    dbus::MessageWriter writer(&method_call);
    writer.AppendString(account_id);
    writer.AppendBool(should_backup_log);

    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void SetArcCpuRestriction(
      login_manager::ContainerCpuRestrictionState restriction_state,
      chromeos::VoidDBusMethodCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerSetArcCpuRestriction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendUint32(restriction_state);
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void EmitArcBooted(const cryptohome::AccountIdentifier& cryptohome_id,
                     chromeos::VoidDBusMethodCallback callback) override {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerEmitArcBooted);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(cryptohome_id.account_id());
    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void GetArcStartTime(
      chromeos::DBusMethodCallback<base::TimeTicks> callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerGetArcStartTimeTicks);

    session_manager_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnGetArcStartTime,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void EnableAdbSideload(EnableAdbSideloadCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerEnableAdbSideload);

    session_manager_proxy_->CallMethodWithErrorResponse(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnEnableAdbSideload,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void QueryAdbSideload(QueryAdbSideloadCallback callback) override {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerQueryAdbSideload);

    session_manager_proxy_->CallMethodWithErrorResponse(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnQueryAdbSideload,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void Init(dbus::Bus* bus) {
    session_manager_proxy_ = bus->GetObjectProxy(
        login_manager::kSessionManagerServiceName,
        dbus::ObjectPath(login_manager::kSessionManagerServicePath));
    blocking_method_caller_ = std::make_unique<chromeos::BlockingMethodCaller>(
        bus, session_manager_proxy_);

    // Signals emitted on the session manager's interface.
    session_manager_proxy_->ConnectToSignal(
        login_manager::kSessionManagerInterface,
        login_manager::kOwnerKeySetSignal,
        base::BindRepeating(&SessionManagerClientImpl::OwnerKeySetReceived,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&SessionManagerClientImpl::SignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));
    session_manager_proxy_->ConnectToSignal(
        login_manager::kSessionManagerInterface,
        login_manager::kPropertyChangeCompleteSignal,
        base::BindRepeating(
            &SessionManagerClientImpl::PropertyChangeCompleteReceived,
            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&SessionManagerClientImpl::SignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));
    session_manager_proxy_->ConnectToSignal(
        login_manager::kSessionManagerInterface,
        login_manager::kScreenIsLockedSignal,
        base::BindRepeating(&SessionManagerClientImpl::ScreenIsLockedReceived,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&SessionManagerClientImpl::SignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));
    session_manager_proxy_->ConnectToSignal(
        login_manager::kSessionManagerInterface,
        login_manager::kScreenIsUnlockedSignal,
        base::BindRepeating(&SessionManagerClientImpl::ScreenIsUnlockedReceived,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&SessionManagerClientImpl::SignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));
    session_manager_proxy_->ConnectToSignal(
        login_manager::kSessionManagerInterface,
        login_manager::kArcInstanceStopped,
        base::BindRepeating(
            &SessionManagerClientImpl::ArcInstanceStoppedReceived,
            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&SessionManagerClientImpl::SignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));

    session_manager_proxy_->ConnectToSignal(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionStateChangedSignal,
        base::BindRepeating(&SessionManagerClientImpl::SessionStateChanged,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&SessionManagerClientImpl::SignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));
  }

 private:
  // Makes a method call to the session manager with no arguments and no
  // response.
  void SimpleMethodCallToSessionManager(const std::string& method_name) {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 method_name);
    session_manager_proxy_->CallMethod(&method_call,
                                       dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                       base::DoNothing());
  }

  // Called when the method call without result is completed.
  void OnVoidMethod(chromeos::VoidDBusMethodCallback callback,
                    dbus::Response* response) {
    std::move(callback).Run(response);
  }

  // Non-blocking call to Session Manager to retrieve policy.
  void CallRetrievePolicy(const login_manager::PolicyDescriptor& descriptor,
                          RetrievePolicyCallback callback) {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerRetrievePolicyEx);
    dbus::MessageWriter writer(&method_call);
    const std::string descriptor_blob = descriptor.SerializeAsString();
    // static_cast does not work due to signedness.
    writer.AppendArrayOfBytes(base::as_byte_span(descriptor_blob));
    session_manager_proxy_->CallMethodWithErrorResponse(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&SessionManagerClientImpl::OnRetrievePolicy,
                       weak_ptr_factory_.GetWeakPtr(),
                       descriptor.account_type(), std::move(callback)));
  }

  // Blocking call to Session Manager to retrieve policy.
  RetrievePolicyResponseType CallBlockingRetrievePolicy(
      const login_manager::PolicyDescriptor& descriptor,
      std::string* policy_out) {
    dbus::MethodCall method_call(
        login_manager::kSessionManagerInterface,
        login_manager::kSessionManagerRetrievePolicyEx);
    dbus::MessageWriter writer(&method_call);
    const std::string descriptor_blob = descriptor.SerializeAsString();
    // static_cast does not work due to signedness.
    writer.AppendArrayOfBytes(base::as_byte_span(descriptor_blob));
    auto result = blocking_method_caller_->CallMethodAndBlock(&method_call);
    RetrievePolicyResponseType response_type =
        RetrievePolicyResponseType::SUCCESS;
    if (!result.has_value() && result.error().IsValid()) {
      response_type = GetPolicyResponseTypeByError(result.error().name());
    }
    if (response_type == RetrievePolicyResponseType::SUCCESS) {
      ExtractPolicyResponseString(descriptor.account_type(),
                                  result.has_value() ? result->get() : nullptr,
                                  policy_out);
    } else {
      policy_out->clear();
    }
    return response_type;
  }

  void CallStorePolicy(const login_manager::PolicyDescriptor& descriptor,
                       const std::string& policy_blob,
                       chromeos::VoidDBusMethodCallback callback) {
    dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
                                 login_manager::kSessionManagerStorePolicyEx);
    dbus::MessageWriter writer(&method_call);
    const std::string descriptor_blob = descriptor.SerializeAsString();
    // static_cast does not work due to signedness.
    writer.AppendArrayOfBytes(base::as_byte_span(descriptor_blob));
    writer.AppendArrayOfBytes(base::as_byte_span(policy_blob));
    // The timeout is intentionally chosen to be that big because on some
    // devices the operation is slow and a short timeout would lead to
    // unnecessary enrollment failures. See crbug.com/1155533 for context.
    session_manager_proxy_->CallMethod(
        &method_call, /*timeout_ms=*/180000,
        base::BindOnce(&SessionManagerClientImpl::OnVoidMethod,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  // Called when kSessionManagerRetrieveActiveSessions method is complete.
  void OnRetrieveActiveSessions(const std::string& method_name,
                                ActiveSessionsCallback callback,
                                dbus::Response* response) {
    if (!response) {
      std::move(callback).Run(std::nullopt);
      return;
    }

    dbus::MessageReader reader(response);
    dbus::MessageReader array_reader(nullptr);
    if (!reader.PopArray(&array_reader)) {
      LOG(ERROR) << method_name
                 << " response is incorrect: " << response->ToString();
      std::move(callback).Run(std::nullopt);
      return;
    }

    ActiveSessionsMap sessions;
    while (array_reader.HasMoreData()) {
      dbus::MessageReader dict_entry_reader(nullptr);
      std::string key;
      std::string value;
      if (!array_reader.PopDictEntry(&dict_entry_reader) ||
          !dict_entry_reader.PopString(&key) ||
          !dict_entry_reader.PopString(&value)) {
        LOG(ERROR) << method_name
                   << " response is incorrect: " << response->ToString();
      } else {
        sessions[key] = value;
      }
    }
    std::move(callback).Run(std::move(sessions));
  }

  void OnLoginScreenStorageStore(LoginScreenStorageStoreCallback callback,
                                 dbus::Response* response) {
    std::move(callback).Run(std::nullopt);
  }

  void OnLoginScreenStorageRetrieve(LoginScreenStorageRetrieveCallback callback,
                                    dbus::Response* response) {
    if (!response) {
      std::move(callback).Run(std::nullopt /* data */,
                              "LoginScreenStorageRetrieve() D-Bus method "
                              "returned an empty response");
      return;
    }

    dbus::MessageReader reader(response);
    base::ScopedFD result_fd;
    uint64_t result_size;
    if (!reader.PopUint64(&result_size) ||
        !reader.PopFileDescriptor(&result_fd)) {
      std::string error = "Invalid response: " + response->ToString();
      std::move(callback).Run(std::nullopt /* data */, error);
      return;
    }
    std::vector<uint8_t> result_data;
    if (!ReadSecretFromSharedMemory(std::move(result_fd), result_size,
                                    &result_data)) {
      std::string error = "Couldn't read retrieved data from shared memory.";
      std::move(callback).Run(std::nullopt /* data */, error);
      return;
    }
    std::move(callback).Run(std::string(result_data.begin(), result_data.end()),
                            std::nullopt /* error */);
  }

  void OnLoginScreenStorageListKeys(LoginScreenStorageListKeysCallback callback,
                                    dbus::Response* response) {
    if (!response) {
      // TODO(voit): Add more granular error handling: key is not found error vs
      // general 'something went wrong' error.
      std::move(callback).Run({} /* keys */,
                              "LoginScreenStorageListKeys() D-Bus method "
                              "returned an empty response");
      return;
    }
    dbus::MessageReader reader(response);
    std::vector<std::string> keys;
    if (!reader.PopArrayOfStrings(&keys)) {
      std::string error = "Invalid response: " + response->ToString();
      std::move(callback).Run({} /* keys */, error);
      return;
    }
    std::move(callback).Run(std::move(keys), std::nullopt /* error */);
  }

  // Reads an array of policy data bytes data as std::string.
  void ExtractPolicyResponseString(
      login_manager::PolicyAccountType account_type,
      dbus::Response* response,
      std::string* extracted) {
    if (!response) {
      LOG(ERROR) << "Failed to call RetrievePolicyEx for account type "
                 << account_type;
      return;
    }
    dbus::MessageReader reader(response);
    const uint8_t* values = nullptr;
    size_t length = 0;
    if (!reader.PopArrayOfBytes(&values, &length)) {
      LOG(ERROR) << "Invalid response: " << response->ToString();
      return;
    }
    // static_cast does not work due to signedness.
    extracted->assign(reinterpret_cast<const char*>(values), length);
  }

  // Called when kSessionManagerRetrievePolicy or
  // kSessionManagerRetrievePolicyForUser method is complete.
  void OnRetrievePolicy(login_manager::PolicyAccountType account_type,
                        RetrievePolicyCallback callback,
                        dbus::Response* response,
                        dbus::ErrorResponse* error) {
    if (!response) {
      RetrievePolicyResponseType response_type =
          GetPolicyResponseTypeByError(error ? error->GetErrorName() : "");
      std::move(callback).Run(response_type, std::string());
      return;
    }

    dbus::MessageReader reader(response);
    std::string proto_blob;
    ExtractPolicyResponseString(account_type, response, &proto_blob);
    std::move(callback).Run(RetrievePolicyResponseType::SUCCESS, proto_blob);
  }

  // Called when the owner key set signal is received.
  void OwnerKeySetReceived(dbus::Signal* signal) {
    dbus::MessageReader reader(signal);
    std::string result_string;
    if (!reader.PopString(&result_string)) {
      LOG(ERROR) << "Invalid signal: " << signal->ToString();
      return;
    }
    const bool success = base::StartsWith(result_string, "success",
                                          base::CompareCase::INSENSITIVE_ASCII);
    for (auto& observer : observers_)
      observer.OwnerKeySet(success);
  }

  // Called when the property change complete signal is received.
  void PropertyChangeCompleteReceived(dbus::Signal* signal) {
    dbus::MessageReader reader(signal);
    std::string result_string;
    if (!reader.PopString(&result_string)) {
      LOG(ERROR) << "Invalid signal: " << signal->ToString();
      return;
    }
    const bool success = base::StartsWith(result_string, "success",
                                          base::CompareCase::INSENSITIVE_ASCII);
    for (auto& observer : observers_)
      observer.PropertyChangeComplete(success);
  }

  void ScreenIsLockedReceived(dbus::Signal* signal) {
    screen_is_locked_ = true;
    for (auto& observer : observers_)
      observer.ScreenLockedStateUpdated();
  }

  void ScreenIsUnlockedReceived(dbus::Signal* signal) {
    screen_is_locked_ = false;
    for (auto& observer : observers_)
      observer.ScreenLockedStateUpdated();
  }

  void ArcInstanceStoppedReceived(dbus::Signal* signal) {
    dbus::MessageReader reader(signal);
    uint32_t reason = 0;
    if (!reader.PopUint32(&reason)) {
      LOG(ERROR) << "Invalid signal: " << signal->ToString();
      return;
    }
    for (auto& observer : observers_) {
      observer.ArcInstanceStopped(
          static_cast<login_manager::ArcContainerStopReason>(reason));
    }
  }

  void SessionStateChanged(dbus::Signal* signal) {
    dbus::MessageReader reader(signal);
    std::string result_string;
    if (!reader.PopString(&result_string)) {
      LOG(ERROR) << "Invalid signal: " << signal->ToString();
      return;
    }
    if (result_string == kStopping) {
      for (auto& observer : observers_) {
        observer.SessionStopping();
      }
    }
  }

  // Called when the object is connected to the signal.
  void SignalConnected(const std::string& interface_name,
                       const std::string& signal_name,
                       bool success) {
    LOG_IF(ERROR, !success) << "Failed to connect to " << signal_name;
  }

  // Called when kSessionManagerGetServerBackedStateKeys method is complete.
  void OnGetServerBackedStateKeys(StateKeysCallback callback,
                                  dbus::Response* response,
                                  dbus::ErrorResponse* error_response) {
    if (error_response &&
        error_response->GetErrorName() ==
            login_manager::dbus_error::kStateKeysRequestFail) {
      // Session manager failed to generate state keys, report identifiers
      // error.
      return std::move(callback).Run(
          base::unexpected(StateKeyErrorType::kMissingIdentifiers));
    }

    if (!response) {
      // DBus call failed with unspecified error, report communication error.
      return std::move(callback).Run(
          base::unexpected(StateKeyErrorType::kCommunicationError));
    }

    dbus::MessageReader reader(response);
    dbus::MessageReader array_reader(nullptr);
    if (!reader.PopArray(&array_reader)) {
      LOG(ERROR) << "Bad response (not an array of keys): "
                 << response->ToString();
      std::move(callback).Run(
          base::unexpected(StateKeyErrorType::kInvalidResponse));
      return;
    }

    std::vector<std::string> state_keys;
    while (array_reader.HasMoreData()) {
      const uint8_t* data = nullptr;
      size_t size = 0;
      if (!array_reader.PopArrayOfBytes(&data, &size)) {
        LOG(ERROR) << "Bad response (not an array of bytes): "
                   << response->ToString();
        std::move(callback).Run(
            base::unexpected(StateKeyErrorType::kInvalidResponse));
        return;
      }
      if (size == 0) {
        LOG(ERROR) << "Bad response (empty array of bytes): "
                   << response->ToString();
        std::move(callback).Run(
            base::unexpected(StateKeyErrorType::kInvalidResponse));
        return;
      }
      state_keys.emplace_back(reinterpret_cast<const char*>(data), size);
    }

    if (state_keys.empty()) {
      // TODO(b/318708647): Session manager did not report an error but still
      // responded with empty state keys. Report something else than missing
      // identifiers.
      std::move(callback).Run(
          base::unexpected(StateKeyErrorType::kMissingIdentifiers));
      return;
    }
    std::move(callback).Run(base::ok(std::move(state_keys)));
  }

  // Called when kSessionManagerGetPsmDeviceActiveSecret method is complete.
  void OnGetPsmDeviceActiveSecret(PsmDeviceActiveSecretCallback callback,
                                  dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to get response OnGetPsmDeviceActiveSecret.";
      std::move(callback).Run(std::string());
      return;
    }

    std::string psm_device_active_secret;
    dbus::MessageReader reader(response);

    if (!reader.PopString(&psm_device_active_secret)) {
      LOG(ERROR) << "Received a non-string response from dbus.";
      std::move(callback).Run(std::string());
      return;
    }

    std::move(callback).Run(psm_device_active_secret);
  }

  void OnGetArcStartTime(chromeos::DBusMethodCallback<base::TimeTicks> callback,
                         dbus::Response* response) {
    if (!response) {
      std::move(callback).Run(std::nullopt);
      return;
    }

    dbus::MessageReader reader(response);
    int64_t ticks = 0;
    if (!reader.PopInt64(&ticks)) {
      LOG(ERROR) << "Invalid response: " << response->ToString();
      std::move(callback).Run(std::nullopt);
      return;
    }

    std::move(callback).Run(base::TimeTicks::FromInternalValue(ticks));
  }

  void OnEnableAdbSideload(EnableAdbSideloadCallback callback,
                           dbus::Response* response,
                           dbus::ErrorResponse* error) {
    if (!response) {
      LOG(ERROR) << "Failed to call EnableAdbSideload: "
                 << (error ? error->ToString() : "(null)");
      if (error && error->GetErrorName() == DBUS_ERROR_NOT_SUPPORTED) {
        std::move(callback).Run(AdbSideloadResponseCode::NEED_POWERWASH);
      } else {
        std::move(callback).Run(AdbSideloadResponseCode::FAILED);
      }
      return;
    }

    bool succeeded;
    dbus::MessageReader reader(response);
    if (!reader.PopBool(&succeeded)) {
      LOG(ERROR) << "Failed to enable sideloading";
      std::move(callback).Run(AdbSideloadResponseCode::FAILED);
      return;
    }
    std::move(callback).Run(AdbSideloadResponseCode::SUCCESS);
  }

  void OnQueryAdbSideload(QueryAdbSideloadCallback callback,
                          dbus::Response* response,
                          dbus::ErrorResponse* error) {
    if (!response) {
      LOG(ERROR) << "Failed to call QueryAdbSideload: "
                 << (error ? error->ToString() : "(null)");
      if (error && error->GetErrorName() == DBUS_ERROR_NOT_SUPPORTED) {
        std::move(callback).Run(AdbSideloadResponseCode::NEED_POWERWASH, false);
      } else {
        std::move(callback).Run(AdbSideloadResponseCode::FAILED, false);
      }
      return;
    }

    bool is_allowed;
    dbus::MessageReader reader(response);
    if (!reader.PopBool(&is_allowed)) {
      LOG(ERROR) << "Failed to interpret the response";
      std::move(callback).Run(AdbSideloadResponseCode::FAILED, false);
      return;
    }
    std::move(callback).Run(AdbSideloadResponseCode::SUCCESS, is_allowed);
  }

  raw_ptr<dbus::ObjectProxy> session_manager_proxy_ = nullptr;
  std::unique_ptr<chromeos::BlockingMethodCaller> blocking_method_caller_;
  base::ObserverList<Observer>::UncheckedAndDanglingUntriaged observers_{
      SessionManagerClient::kObserverListPolicy};

  // Most recent screen-lock state received from session_manager.
  bool screen_is_locked_ = false;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<SessionManagerClientImpl> weak_ptr_factory_{this};
};

SessionManagerClient::SessionManagerClient() {
  DCHECK(!g_instance);
  g_instance = this;
}

SessionManagerClient::~SessionManagerClient() {
  DCHECK_EQ(this, g_instance);
  g_instance = nullptr;
}

// static
void SessionManagerClient::Initialize(dbus::Bus* bus) {
  DCHECK(bus);
  (new SessionManagerClientImpl)->Init(bus);
}

// static
void SessionManagerClient::InitializeFake() {
  // Do not create a new fake if it was initialized early in a browser test (for
  // early setup calls dependent on SessionManagerClient).
  if (!FakeSessionManagerClient::Get()) {
    new FakeSessionManagerClient(
        FakeSessionManagerClient::PolicyStorageType::kOnDisk);
  }
}

// static
void SessionManagerClient::InitializeFakeInMemory() {
  if (!FakeSessionManagerClient::Get()) {
    new FakeSessionManagerClient(
        FakeSessionManagerClient::PolicyStorageType::kInMemory);
  }
}

// static
void SessionManagerClient::Shutdown() {
  // Note `g_instance` could be nullptr when ScopedFakeSessionManagerClient is
  // used.
  delete g_instance;
}

// static
SessionManagerClient* SessionManagerClient::Get() {
  return g_instance;
}

}  // namespace ash