File: cellular_policy_handler.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 (694 lines) | stat: -rw-r--r-- 27,141 bytes parent folder | download | duplicates (8)
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/network/cellular_policy_handler.h"

#include <optional>

#include "base/containers/contains.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "base/value_iterators.h"
#include "chromeos/ash/components/dbus/hermes/hermes_euicc_client.h"
#include "chromeos/ash/components/dbus/hermes/hermes_manager_client.h"
#include "chromeos/ash/components/dbus/hermes/hermes_profile_client.h"
#include "chromeos/ash/components/network/cellular_esim_installer.h"
#include "chromeos/ash/components/network/cellular_esim_profile_handler.h"
#include "chromeos/ash/components/network/cellular_esim_profile_waiter.h"
#include "chromeos/ash/components/network/cellular_utils.h"
#include "chromeos/ash/components/network/managed_cellular_pref_handler.h"
#include "chromeos/ash/components/network/managed_network_configuration_handler.h"
#include "chromeos/ash/components/network/metrics/cellular_network_metrics_logger.h"
#include "chromeos/ash/components/network/network_event_log.h"
#include "chromeos/ash/components/network/network_profile_handler.h"
#include "chromeos/ash/components/network/network_state_handler.h"
#include "chromeos/ash/components/network/policy_util.h"
#include "chromeos/ash/services/cellular_setup/public/mojom/esim_manager.mojom.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

using ash::cellular_setup::mojom::ProfileInstallMethod;

namespace ash {

namespace {

constexpr int kInstallRetryLimit = 3;
constexpr base::TimeDelta kInstallRetryDelay = base::Days(1);

// The timeout that is provided when waiting for the properties of discovered
// pending profiles to be set before choosing a profile to install.
constexpr base::TimeDelta kCellularESimProfileWaiterDelay = base::Seconds(30);

constexpr net::BackoffEntry::Policy kRetryBackoffPolicy = {
    0,               // Number of initial errors to ignore.
    5 * 60 * 1000,   // Initial delay of 5 minutes in ms.
    2.0,             // Factor by which the waiting time will be multiplied.
    0,               // Fuzzing percentage.
    60 * 60 * 1000,  // Maximum delay of 1 hour in ms.
    -1,              // Never discard the entry.
    true,            // Use initial delay.
};

// Timeout waiting for EUICC to become available in Hermes.
constexpr base::TimeDelta kEuiccWaitTime = base::Minutes(3);
// Timeout waiting for cellular device to become available.
constexpr base::TimeDelta kCellularDeviceWaitTime = base::Seconds(30);

// Returns the activation code for the first eSIM profile whose properties are
// available and whose state is pending, if any.
std::optional<std::string> GetFirstActivationCode(
    const dbus::ObjectPath& euicc_path,
    const std::vector<dbus::ObjectPath>& profile_paths) {
  HermesEuiccClient::Properties* euicc_properties =
      HermesEuiccClient::Get()->GetProperties(euicc_path);
  DCHECK(euicc_properties);

  for (const auto& profile_path : profile_paths) {
    HermesProfileClient::Properties* profile_properties =
        HermesProfileClient::Get()->GetProperties(profile_path);
    if (!profile_properties) {
      NET_LOG(ERROR)
          << "Failed to get profile properties for available profile";
      continue;
    }
    if (profile_properties->state().value() !=
        hermes::profile::State::kPending) {
      NET_LOG(ERROR) << "Expected available profile to have state "
                     << hermes::profile::State::kPending << ", has "
                     << profile_properties->state().value();
      continue;
    }
    const std::string& activation_code =
        profile_properties->activation_code().value();
    if (activation_code.empty()) {
      NET_LOG(ERROR) << "Expected available profile to have an activation code";
      continue;
    }
    return activation_code;
  }
  return std::nullopt;
}

}  // namespace

CellularPolicyHandler::InstallPolicyESimRequest::InstallPolicyESimRequest(
    policy_util::SmdxActivationCode activation_code,
    const base::Value::Dict& onc_config)
    : activation_code(std::move(activation_code)),
      onc_config(onc_config.Clone()),
      retry_backoff(&kRetryBackoffPolicy) {}

CellularPolicyHandler::InstallPolicyESimRequest::~InstallPolicyESimRequest() =
    default;

CellularPolicyHandler::CellularPolicyHandler() = default;

CellularPolicyHandler::~CellularPolicyHandler() {
  OnShuttingDown();
}

void CellularPolicyHandler::Init(
    CellularESimProfileHandler* cellular_esim_profile_handler,
    CellularESimInstaller* cellular_esim_installer,
    CellularInhibitor* cellular_inhibitor,
    NetworkProfileHandler* network_profile_handler,
    NetworkStateHandler* network_state_handler,
    ManagedCellularPrefHandler* managed_cellular_pref_handler,
    ManagedNetworkConfigurationHandler* managed_network_configuration_handler) {
  cellular_esim_profile_handler_ = cellular_esim_profile_handler;
  cellular_esim_installer_ = cellular_esim_installer;
  cellular_inhibitor_ = cellular_inhibitor;
  network_profile_handler_ = network_profile_handler;
  network_state_handler_ = network_state_handler;
  managed_cellular_pref_handler_ = managed_cellular_pref_handler;
  managed_network_configuration_handler_ =
      managed_network_configuration_handler;

  hermes_observation_.Observe(HermesManagerClient::Get());
  cellular_esim_profile_handler_observation_.Observe(
      cellular_esim_profile_handler);
  network_state_handler_observer_.Observe(network_state_handler_.get());
}

void CellularPolicyHandler::InstallESim(const base::Value::Dict& onc_config) {
  std::optional<policy_util::SmdxActivationCode> activation_code =
      policy_util::GetSmdxActivationCodeFromONC(onc_config);

  if (!activation_code.has_value()) {
    return;
  }

  NET_LOG(EVENT) << "Queueing a policy eSIM profile installation request with "
                 << "activation code found in the provided ONC configuration: "
                 << activation_code->ToString();

  PushRequestAndProcess(std::make_unique<InstallPolicyESimRequest>(
      std::move(activation_code.value()), onc_config));
}

void CellularPolicyHandler::OnAvailableEuiccListChanged() {
  ResumeInstallIfNeeded();
}

void CellularPolicyHandler::OnESimProfileListUpdated() {
  ResumeInstallIfNeeded();
}

void CellularPolicyHandler::DeviceListChanged() {
  ResumeInstallIfNeeded();
}

void CellularPolicyHandler::OnShuttingDown() {
  if (!network_state_handler_) {
    return;
  }
  network_state_handler_observer_.Reset();
  network_state_handler_ = nullptr;
}

void CellularPolicyHandler::ResumeInstallIfNeeded() {
  if (!is_installing_ || !wait_timer_.IsRunning()) {
    return;
  }
  wait_timer_.Stop();
  AttemptInstallESim();
}

void CellularPolicyHandler::ProcessRequests() {
  if (remaining_install_requests_.empty()) {
    need_refresh_profile_list_ = true;
    return;
  }

  // Another install request is already underway; wait until it has completed
  // before starting a new request.
  if (is_installing_)
    return;

  is_installing_ = true;
  NET_LOG(EVENT) << "Installing policy eSIM profile: "
                 << GetCurrentActivationCode().ToString();
  AttemptInstallESim();
}

void CellularPolicyHandler::ScheduleRetryAndProcessRequests(
    std::unique_ptr<InstallPolicyESimRequest> request,
    InstallRetryReason reason) {
  if (reason != InstallRetryReason::kInternalError &&
      request->retry_backoff.failure_count() >= kInstallRetryLimit) {
    NET_LOG(ERROR) << "Failed to install policy eSIM profile: "
                   << request->activation_code.ToErrorString();
    ProcessRequests();
    return;
  }

  request->retry_backoff.InformOfRequest(/*succeeded=*/false);

  // Force a delay of |kInstallRetryDelay| when we fail for any reason other
  // than an internal failure, e.g. failure to inhibit, to reduce frequent
  // retries due to errors that are unlikely to be resolved quickly, e.g. an
  // invalid activation code.
  if (reason == InstallRetryReason::kOther) {
    request->retry_backoff.SetCustomReleaseTime(base::TimeTicks::Now() +
                                                kInstallRetryDelay);
  }

  const base::TimeDelta retry_delay =
      request->retry_backoff.GetTimeUntilRelease();

  NET_LOG(ERROR) << "Failed to install policy eSIM profile. Retrying in "
                 << retry_delay << ": "
                 << request->activation_code.ToErrorString();

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&CellularPolicyHandler::PushRequestAndProcess,
                     weak_ptr_factory_.GetWeakPtr(), std::move(request)),
      retry_delay);

  ProcessRequests();
}

void CellularPolicyHandler::PushRequestAndProcess(
    std::unique_ptr<InstallPolicyESimRequest> request) {
  remaining_install_requests_.push_back(std::move(request));
  ProcessRequests();
}

void CellularPolicyHandler::PopRequest() {
  remaining_install_requests_.pop_front();
  is_installing_ = false;
  if (remaining_install_requests_.empty()) {
    const NetworkProfile* profile =
        cellular_utils::GetCellularProfile(network_profile_handler_);
    DCHECK(profile);

    managed_network_configuration_handler_->OnCellularPoliciesApplied(*profile);
  }
}

void CellularPolicyHandler::PopAndProcessRequests() {
  PopRequest();
  ProcessRequests();
}

void CellularPolicyHandler::AttemptInstallESim() {
  DCHECK(is_installing_);

  const DeviceState* cellular_device =
      network_state_handler_->GetDeviceStateByType(
          NetworkTypePattern::Cellular());
  if (!cellular_device) {
    // Cellular device may not be ready. Wait for DeviceListChanged notification
    // before continuing with installation.
    NET_LOG(EVENT)
        << "Waiting for the cellular device to become available to install "
        << "policy eSIM profile: " << GetCurrentActivationCode().ToString();
    wait_timer_.Start(FROM_HERE, kCellularDeviceWaitTime,
                      base::BindOnce(&CellularPolicyHandler::OnWaitTimeout,
                                     weak_ptr_factory_.GetWeakPtr()));
    return;
  }

  std::optional<dbus::ObjectPath> euicc_path =
      cellular_utils::GetCurrentEuiccPath();
  if (!euicc_path) {
    // Hermes may not be ready and available EUICC list is empty. Wait for
    // AvailableEuiccListChanged notification to continue with installation.
    NET_LOG(EVENT) << "Waiting for EUICC to be found to install policy eSIM "
                   << "profile: " << GetCurrentActivationCode().ToString();
    wait_timer_.Start(FROM_HERE, kEuiccWaitTime,
                      base::BindOnce(&CellularPolicyHandler::OnWaitTimeout,
                                     weak_ptr_factory_.GetWeakPtr()));
    return;
  }

  base::Value::Dict new_shill_properties = GetNewShillProperties();
  // If iccid is found in policy onc, the installation will be skipped because
  // it indicates that the eSIM profile has already been installed before using
  // the same SM-DP+ or SM-DS.
  const std::optional<std::string> iccid = GetIccidFromPolicyONC();
  if (iccid) {
    const std::optional<dbus::ObjectPath> profile_path =
        FindExistingMatchingESimProfile(*iccid);
    if (profile_path) {
      NET_LOG(EVENT) << "Found an existing installed profile that matches the "
                     << "policy eSIM installation request. Configuring a Shill "
                     << "service for the profile: "
                     << GetCurrentActivationCode().ToString();
      cellular_esim_installer_->ConfigureESimService(
          std::move(new_shill_properties), *euicc_path, *profile_path,
          base::BindOnce(&CellularPolicyHandler::OnConfigureESimService,
                         weak_ptr_factory_.GetWeakPtr()));
      return;
    }

    NET_LOG(EVENT) << "Skip installation because iccid is found in the policy"
                   << " ONC, this indicates that the eSIM profile has already"
                   << " been installed.";
    PopAndProcessRequests();
    return;
  }

  if (!HasNonCellularInternetConnectivity()) {
    NET_LOG(ERROR)
        << "Failed to install the policy eSIM profile due to missing a "
        << "non-cellular internet connection: "
        << GetCurrentActivationCode().ToErrorString();
    auto current_request = std::move(remaining_install_requests_.front());
    PopRequest();
    ScheduleRetryAndProcessRequests(
        std::move(current_request),
        InstallRetryReason::kMissingNonCellularConnectivity);
    return;
  }

  if (need_refresh_profile_list_) {
    // Profile list for current EUICC may not have been refreshed, so explicitly
    // refresh profile list before processing installation requests.
    cellular_esim_profile_handler_->RefreshProfileListAndRestoreSlot(
        *euicc_path,
        base::BindOnce(&CellularPolicyHandler::OnRefreshProfileList,
                       weak_ptr_factory_.GetWeakPtr(), *euicc_path,
                       std::move(new_shill_properties)));
    return;
  }

  PerformInstallESim(*euicc_path, std::move(new_shill_properties));
}

void CellularPolicyHandler::PerformInstallESim(
    const dbus::ObjectPath& euicc_path,
    base::Value::Dict new_shill_properties) {
  NET_LOG(EVENT) << "Installing policy eSIM profile ("
                 << GetCurrentActivationCode().ToString() << ") and inhibiting "
                 << "cellular device to request available profiles for SM-DX "
                    "activation code.";

  // Confirmation codes are not required when installing policy eSIM profiles.
  cellular_inhibitor_->InhibitCellularScanning(
      CellularInhibitor::InhibitReason::kRequestingAvailableProfiles,
      base::BindOnce(&CellularPolicyHandler::OnInhibitedForRefreshSmdxProfiles,
                     weak_ptr_factory_.GetWeakPtr(), euicc_path,
                     std::move(new_shill_properties)));
}

void CellularPolicyHandler::OnRefreshProfileList(
    const dbus::ObjectPath& euicc_path,
    base::Value::Dict new_shill_properties,
    std::unique_ptr<CellularInhibitor::InhibitLock> inhibit_lock) {
  if (!inhibit_lock) {
    NET_LOG(ERROR) << "Failed to refresh the profile list due to an inhibit "
                   << "error, path: " << euicc_path.value();
  } else {
    need_refresh_profile_list_ = false;
    // Reset the |inhibit_lock| so that the device will no longer be inhibited
    // with |kRefreshingProfileList| and can become inhibited with the correct
    // reason e.g., |kInstallingProfile|.
    inhibit_lock.reset();
  }

  PerformInstallESim(euicc_path, std::move(new_shill_properties));
}

void CellularPolicyHandler::OnConfigureESimService(
    std::optional<dbus::ObjectPath> service_path) {
  DCHECK(is_installing_);

  auto current_request = std::move(remaining_install_requests_.front());
  PopRequest();
  if (!service_path) {
    ScheduleRetryAndProcessRequests(std::move(current_request),
                                    InstallRetryReason::kOther);
    return;
  }

  NET_LOG(EVENT) << "Successfully configured a Shill service for the existing "
                 << "profile: " << current_request->activation_code.ToString();

  current_request->retry_backoff.InformOfRequest(/*succeeded=*/true);
  const std::string* iccid =
      policy_util::GetIccidFromONC(current_request->onc_config);
  DCHECK(iccid);

  const std::string* name =
      current_request->onc_config.FindString(::onc::network_config::kName);
  DCHECK(name);
  managed_cellular_pref_handler_->AddESimMetadata(
      *iccid, *name, current_request->activation_code);
  ProcessRequests();
}

void CellularPolicyHandler::OnInhibitedForRefreshSmdxProfiles(
    const dbus::ObjectPath& euicc_path,
    base::Value::Dict new_shill_properties,
    std::unique_ptr<CellularInhibitor::InhibitLock> inhibit_lock) {
  // The cellular device must be inhibited before refreshing SM-DX profiles. If
  // we fail to receive a lock consider this installation attempt a failure.
  if (!inhibit_lock) {
    NET_LOG(ERROR)
        << "Failed to inhibit cellular for refreshing SM-DX profiles";
    auto current_request = std::move(remaining_install_requests_.front());

    if (current_request->activation_code.type() ==
        policy_util::SmdxActivationCode::Type::SMDS) {
      CellularNetworkMetricsLogger::LogSmdsScanResult(
          current_request->activation_code.value(),
          /*result=*/std::nullopt);
    }
    PopRequest();
    ScheduleRetryAndProcessRequests(std::move(current_request),
                                    InstallRetryReason::kInternalError);
    return;
  }

  HermesEuiccClient::Get()->RefreshSmdxProfiles(
      euicc_path, GetCurrentActivationCode().value(),
      /*restore_slot=*/true,
      base::BindOnce(&CellularPolicyHandler::OnRefreshSmdxProfiles,
                     weak_ptr_factory_.GetWeakPtr(), euicc_path,
                     std::move(new_shill_properties), std::move(inhibit_lock),
                     base::TimeTicks::Now()));
}

void CellularPolicyHandler::OnRefreshSmdxProfiles(
    const dbus::ObjectPath& euicc_path,
    base::Value::Dict new_shill_properties,
    std::unique_ptr<CellularInhibitor::InhibitLock> inhibit_lock,
    base::TimeTicks start_time,
    HermesResponseStatus status,
    const std::vector<dbus::ObjectPath>& profile_paths) {
  DCHECK(inhibit_lock);

  auto& current_request = remaining_install_requests_.front();

  const bool is_smds =
      remaining_install_requests_.front()->activation_code.type() ==
      policy_util::SmdxActivationCode::Type::SMDS;
  if (is_smds) {
    CellularNetworkMetricsLogger::LogSmdsScanResult(
        current_request->activation_code.value(), status);
    CellularNetworkMetricsLogger::LogSmdsScanProfileCount(
        profile_paths.size(),
        CellularNetworkMetricsLogger::SmdsScanMethod::kViaPolicy);
    CellularNetworkMetricsLogger::LogSmdsScanDuration(
        base::TimeTicks::Now() - start_time,
        status == HermesResponseStatus::kSuccess,
        current_request->activation_code.ToString());
  }

  std::unique_ptr<CellularESimProfileWaiter> waiter =
      std::make_unique<CellularESimProfileWaiter>();
  for (const auto& profile_path : profile_paths) {
    waiter->RequirePendingProfile(profile_path);
  }

  auto on_success =
      base::BindOnce(&CellularPolicyHandler::CompleteRefreshSmdxProfiles,
                     weak_ptr_factory_.GetWeakPtr(), euicc_path,
                     std::move(new_shill_properties), std::move(inhibit_lock),
                     status, profile_paths);
  auto on_shutdown =
      base::BindOnce(&CellularPolicyHandler::PopAndProcessRequests,
                     weak_ptr_factory_.GetWeakPtr());

  waiter->Wait(std::move(on_success), std::move(on_shutdown));

  if (waiter->waiting()) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(
            [](std::unique_ptr<CellularESimProfileWaiter> waiter) {
              waiter.reset();
            },
            std::move(waiter)),
        kCellularESimProfileWaiterDelay);
  }
}

void CellularPolicyHandler::CompleteRefreshSmdxProfiles(
    const dbus::ObjectPath& euicc_path,
    base::Value::Dict new_shill_properties,
    std::unique_ptr<CellularInhibitor::InhibitLock> inhibit_lock,
    HermesResponseStatus status,
    const std::vector<dbus::ObjectPath>& profile_paths) {
  DCHECK(inhibit_lock);

  auto& current_request = remaining_install_requests_.front();
  const bool is_smds = current_request->activation_code.type() ==
                       policy_util::SmdxActivationCode::Type::SMDS;

  // Scanning SM-DP+ or SM-DS servers will return both a result and available
  // profiles, with the number of profiles that can be returned dependent on
  // which type of server we are scanning. An error being returned indicates
  // there was an issue when performing the scan, but since it does not
  // invalidate the returned profile(s) we simply log the error, capture the
  // error in our metrics, and continue.
  NET_LOG(EVENT) << "HermesEuiccClient::RefreshSmdxProfiles returned with "
                 << "result code " << status << " when called for policy eSIM "
                 << "profile: " << current_request->activation_code.ToString();

  // The activation code will already be known in the SM-DP+ case, but for the
  // sake of using the same flow both both SM-DP+ and SM-DS we choose an
  // activation code from the results in both cases.
  const std::optional<std::string> activation_code =
      GetFirstActivationCode(euicc_path, profile_paths);

  if (!activation_code.has_value()) {
    CellularNetworkMetricsLogger::LogESimPolicyInstallNoAvailableProfiles(
        is_smds
            ? CellularNetworkMetricsLogger::ESimPolicyInstallMethod::kViaSmds
            : CellularNetworkMetricsLogger::ESimPolicyInstallMethod::kViaSmdp);

    NET_LOG(ERROR) << "Failed to find an available profile that matches the "
                   << "activation code provided by policy: "
                   << current_request->activation_code.ToString();
    auto failed_request = std::move(remaining_install_requests_.front());
    PopRequest();
    // Do not retry if there are no profiles available.
    if (status == HermesResponseStatus::kSuccess) {
      ProcessRequests();
    } else {
      ScheduleRetryAndProcessRequests(
          std::move(failed_request), HermesResponseStatusToRetryReason(status));
    }
    return;
  }

  const bool is_initial_install =
      current_request->retry_backoff.failure_count() == 0;
  if (is_initial_install) {
    CellularNetworkMetricsLogger::LogESimPolicyInstallMethod(
        is_smds
            ? CellularNetworkMetricsLogger::ESimPolicyInstallMethod::kViaSmds
            : CellularNetworkMetricsLogger::ESimPolicyInstallMethod::kViaSmdp);
  }

  // Confirmation codes are not required when installing policy eSIM profiles
  // using an activation code.
  cellular_esim_installer_->InstallProfileFromActivationCode(
      activation_code.value(),
      /*confirmation_code=*/std::string(), euicc_path,
      std::move(new_shill_properties),
      base::BindOnce(
          &CellularPolicyHandler::OnESimProfileInstallAttemptComplete,
          weak_ptr_factory_.GetWeakPtr()),
      is_initial_install,
      is_smds ? ProfileInstallMethod::kViaSmds
              : ProfileInstallMethod::kViaActivationCodeAfterSmds);
}

void CellularPolicyHandler::OnESimProfileInstallAttemptComplete(
    HermesResponseStatus status,
    std::optional<dbus::ObjectPath> profile_path,
    std::optional<std::string> service_path) {
  DCHECK(is_installing_);

  auto current_request = std::move(remaining_install_requests_.front());
  PopRequest();

  const bool has_error = status != HermesResponseStatus::kSuccess;
  const bool was_installed = profile_path.has_value();

  if (has_error && !was_installed) {
    if (!base::Contains(kHermesUserErrorCodes, status)) {
      NET_LOG(ERROR)
          << "Failed to install the policy eSIM profile due to a non-user "
          << "error: " << status << ". Scheduling another attempt: "
          << current_request->activation_code.ToString();
      ScheduleRetryAndProcessRequests(
          std::move(current_request),
          HermesResponseStatusToRetryReason(status));
    } else {
      NET_LOG(ERROR)
          << "Failed to install the policy eSIM profile due to a user error: "
          << status << ". Will not schedule another attempt: "
          << current_request->activation_code.ToString();
      ProcessRequests();
    }
    return;
  }

  if (has_error) {
    NET_LOG(ERROR)
        << "Successfully installed policy eSIM profile but failed to "
        << "subsequently enable or connect to the profile: " << status << ". "
        << "Writing the profile information to device prefs and will not "
        << "schedule another attempt: "
        << current_request->activation_code.ToString();
  } else {
    NET_LOG(EVENT) << "Successfully installed policy eSIM profile: "
                   << current_request->activation_code.ToString();
  }

  current_request->retry_backoff.InformOfRequest(/*succeeded=*/true);
  HermesProfileClient::Properties* profile_properties =
      HermesProfileClient::Get()->GetProperties(*profile_path);

  const std::string* name =
      current_request->onc_config.FindString(::onc::network_config::kName);
  DCHECK(name);
  managed_cellular_pref_handler_->AddESimMetadata(
      profile_properties->iccid().value(), *name,
      current_request->activation_code,
      /*sync_stub_networks=*/false);

  managed_network_configuration_handler_->NotifyPolicyAppliedToNetwork(
      *service_path);

  ProcessRequests();
}

void CellularPolicyHandler::OnWaitTimeout() {
  NET_LOG(ERROR) << "Timed out when waiting for the EUICC or profile list.";

  auto current_request = std::move(remaining_install_requests_.front());
  PopRequest();
  ScheduleRetryAndProcessRequests(std::move(current_request),
                                  InstallRetryReason::kInternalError);
}

base::Value::Dict CellularPolicyHandler::GetNewShillProperties() {
  const NetworkProfile* profile =
      cellular_utils::GetCellularProfile(network_profile_handler_);
  DCHECK(profile);

  const std::string* guid =
      remaining_install_requests_.front()->onc_config.FindString(
          ::onc::network_config::kGUID);
  DCHECK(guid);

  return policy_util::CreateShillConfiguration(
      *profile, *guid, /*global_policy=*/nullptr,
      &(remaining_install_requests_.front()->onc_config),
      /*user_settings=*/nullptr);
}

const policy_util::SmdxActivationCode&
CellularPolicyHandler::GetCurrentActivationCode() const {
  DCHECK(is_installing_);
  return remaining_install_requests_.front()->activation_code;
}

std::optional<std::string> CellularPolicyHandler::GetIccidFromPolicyONC() {
  const std::string* iccid = policy_util::GetIccidFromONC(
      remaining_install_requests_.front()->onc_config);
  if (!iccid || iccid->empty()) {
    return std::nullopt;
  }
  return *iccid;
}

std::optional<dbus::ObjectPath>
CellularPolicyHandler::FindExistingMatchingESimProfile(
    const std::string& iccid) {
  for (CellularESimProfile esim_profile :
       cellular_esim_profile_handler_->GetESimProfiles()) {
    if (esim_profile.iccid() == iccid) {
      return esim_profile.path();
    }
  }
  return std::nullopt;
}

bool CellularPolicyHandler::HasNonCellularInternetConnectivity() {
  const NetworkState* default_network =
      network_state_handler_->DefaultNetwork();
  return default_network && default_network->type() != shill::kTypeCellular &&
         default_network->IsOnline();
}

CellularPolicyHandler::InstallRetryReason
CellularPolicyHandler::HermesResponseStatusToRetryReason(
    HermesResponseStatus status) const {
  if (base::Contains(kHermesInternalErrorCodes, status)) {
    return CellularPolicyHandler::InstallRetryReason::kInternalError;
  }
  if (base::Contains(kHermesUserErrorCodes, status)) {
    return CellularPolicyHandler::InstallRetryReason::kUserError;
  }
  return CellularPolicyHandler::InstallRetryReason::kOther;
}

}  // namespace ash