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

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

#include "base/at_exit.h"
#include "base/base64.h"
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/message_loop/message_pump_type.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/bind_post_task.h"
#include "base/task/single_thread_task_executor.h"
#include "base/task/thread_pool.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "build/build_config.h"
#include "chrome/enterprise_companion/device_management_storage/dm_storage.h"
#include "chrome/enterprise_companion/dm_client.h"
#include "chrome/updater/app/app.h"
#include "chrome/updater/configurator.h"
#include "chrome/updater/constants.h"
#include "chrome/updater/external_constants_default.h"
#include "chrome/updater/ipc/ipc_support.h"
#include "chrome/updater/policy/service.h"
#include "chrome/updater/prefs.h"
#include "chrome/updater/protos/omaha_settings.pb.h"
#include "chrome/updater/service_proxy_factory.h"
#include "chrome/updater/update_service.h"
#include "components/crx_file/crx_verifier.h"
#include "components/policy/core/common/cloud/cloud_policy_validator.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/update_client/unpacker.h"
#include "components/update_client/unzip/in_process_unzipper.h"
#include "third_party/zlib/google/zip.h"

namespace updater::tools {

namespace {

#if BUILDFLAG(IS_POSIX)
constexpr zip::UnzipSymlinkOption kSymlinkOption =
    zip::UnzipSymlinkOption::PRESERVE;
#else
constexpr zip::UnzipSymlinkOption kSymlinkOption =
    zip::UnzipSymlinkOption::DONT_PRESERVE;
#endif

}  // namespace

constexpr char kProductSwitch[] = "product";
constexpr char kBackgroundSwitch[] = "background";
constexpr char kListAppsSwitch[] = "list-apps";
constexpr char kListUpdateSwitch[] = "list-update";
constexpr char kListPoliciesSwitch[] = "list-policies";
constexpr char kListCBCMPoliciesSwitch[] = "list-cbcm-policies";
constexpr char kCBCMPolicyPathSwitch[] = "policy-path";
constexpr char kJSONFormatSwitch[] = "json";
constexpr char kUpdateSwitch[] = "update";
constexpr char kUnpackSwitch[] = "unpack";

namespace updater_policy {

namespace edm = ::wireless_android_enterprise_devicemanagement;

std::ostream& operator<<(std::ostream& os, edm::UpdateValue value) {
  os << base::to_underlying(value) << " ";
  switch (value) {
    case edm::UPDATES_DISABLED:
      return os << "(Disabled)";
    case edm::MANUAL_UPDATES_ONLY:
      return os << "(Manual Updates Only)";
    case edm::AUTOMATIC_UPDATES_ONLY:
      return os << "(Automatic Updates Only)";
    case edm::UPDATES_ENABLED:
    default:
      return os << "(Enabled)";
  }
}

std::ostream& operator<<(std::ostream& os, edm::InstallDefaultValue value) {
  os << base::to_underlying(value) << " ";
  switch (value) {
    case edm::INSTALL_DEFAULT_DISABLED:
      return os << "(Disabled)";
    case edm::INSTALL_DEFAULT_ENABLED_MACHINE_ONLY:
      return os << "(Enabled Machine Only)";
    case edm::INSTALL_DEFAULT_ENABLED:
    default:
      return os << "(Enabled)";
  }
}

std::ostream& operator<<(std::ostream& os, edm::InstallValue value) {
  os << base::to_underlying(value) << " ";
  switch (value) {
    case edm::INSTALL_DISABLED:
      return os << "(Disabled)";
    case edm::INSTALL_ENABLED_MACHINE_ONLY:
      return os << "(Enabled Machine Only)";
    case edm::INSTALL_FORCED:
      return os << "(Forced)";
    case edm::INSTALL_ENABLED:
    default:
      return os << "(Enabled)";
  }
}

scoped_refptr<device_management_storage::DMStorage> GetDMStorage() {
  const base::FilePath storage_path =
      base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
          kCBCMPolicyPathSwitch);
  return storage_path.empty()
             ? device_management_storage::GetDefaultDMStorage()
             : device_management_storage::CreateDMStorage(storage_path);
}

std::unique_ptr<device_management_storage::CachedPolicyInfo>
GetCachedPolicyInfo(
    scoped_refptr<device_management_storage::DMStorage> dm_storage) {
  const base::FilePath policy_info_file =
      dm_storage->policy_cache_folder().AppendUTF8("CachedPolicyInfo");
  auto cached_info =
      std::make_unique<device_management_storage::CachedPolicyInfo>();
  std::string policy_info_data;
  if (base::ReadFileToString(policy_info_file, &policy_info_data)) {
    cached_info->Populate(policy_info_data);
  }
  return cached_info;
}

std::unique_ptr<edm::OmahaSettingsClientProto> GetOmahaPolicySettings() {
  std::string encoded_omaha_policy_type =
      base::Base64Encode("google/machine-level-omaha");

  base::FilePath omaha_policy_file = GetDMStorage()
                                         ->policy_cache_folder()
                                         .AppendUTF8(encoded_omaha_policy_type)
                                         .AppendUTF8("PolicyFetchResponse");
  std::string response_data;
  ::enterprise_management::PolicyFetchResponse response;
  ::enterprise_management::PolicyData policy_data;
  auto omaha_settings = std::make_unique<edm::OmahaSettingsClientProto>();
  if (!base::ReadFileToString(omaha_policy_file, &response_data) ||
      response_data.empty() || !response.ParseFromString(response_data) ||
      !policy_data.ParseFromString(response.policy_data()) ||
      !policy_data.has_policy_value() ||
      !omaha_settings->ParseFromString(policy_data.policy_value())) {
    VLOG(1) << "No Omaha policies.";
    return nullptr;
  }

  return omaha_settings;
}

void PrintCachedPolicy(const base::FilePath& policy_path) {
  std::string policy_type;
  if (!base::Base64Decode(policy_path.BaseName().AsUTF8Unsafe(),
                          &policy_type)) {
    std::cout << "Directory not base64 encoded: [" << policy_path << "]";
    return;
  }

  base::FilePath policy_file = policy_path.AppendUTF8("PolicyFetchResponse");
  std::string response_data;
  ::enterprise_management::PolicyFetchResponse response;
  auto omaha_settings = std::make_unique<edm::OmahaSettingsClientProto>();
  if (!base::ReadFileToString(policy_file, &response_data) ||
      response_data.empty() || !response.ParseFromString(response_data)) {
    std::cout << "  [" << policy_type << "] <not parsable>";
    return;
  }

  scoped_refptr<device_management_storage::DMStorage> storage = GetDMStorage();
  std::unique_ptr<device_management_storage::CachedPolicyInfo> info =
      GetCachedPolicyInfo(storage);
  std::unique_ptr<::policy::CloudPolicyValidatorBase::ValidationResult>
      validation_result =
          enterprise_companion::GetDefaultPolicyFetchResponseValidator().Run(
              storage->GetDmToken(), storage->GetDeviceID(), info->public_key(),
              info->timestamp(), response);
  if (validation_result->status ==
      ::policy::CloudPolicyValidatorBase::VALIDATION_OK) {
    std::cout << "  [" << policy_type << "]: satisfies all validation check."
              << std::endl;
    return;
  }

  std::cout << "  [" << policy_type << "] validation failed: " << std::endl;
  std::cout << "    Policy token: " << validation_result->policy_token
            << std::endl;
  std::cout << "    Validation status: "
            << ::policy::CloudPolicyValidatorBase::StatusToString(
                   validation_result->status)
            << std::endl;
}

void PrintCachedPolicyInfo(
    const device_management_storage::CachedPolicyInfo& cached_info) {
  static constexpr size_t kPrintWidth = 16;

  std::cout << "Cached policy info:" << std::endl;
  std::cout << "  Key version: " << cached_info.key_version() << std::endl;
  std::cout << "  Timestamp: " << cached_info.timestamp() << std::endl;
  std::cout << "  Key data (" << cached_info.public_key().size()
            << " bytes): " << std::endl;
  const std::string key = cached_info.public_key();
  for (size_t i = 0; i < key.size(); ++i) {
    std::cout << std::setfill('0') << std::setw(2) << std::hex
              << static_cast<unsigned int>(0xff & key[i]) << ' ';
    if (i % kPrintWidth == kPrintWidth - 1) {
      std::cout << std::endl;
    }
  }
  std::cout << std::endl;
}

void PrintCBCMPolicies() {
  scoped_refptr<device_management_storage::DMStorage> storage = GetDMStorage();
  if (!storage) {
    std::cerr << "Failed to instantiate DM storage instance." << std::endl;
    return;
  }

  std::cout << "-------------------------------------------------" << std::endl;
  std::cout << "Device ID: " << storage->GetDeviceID() << std::endl;
  std::cout << "Enrollment token: " << storage->GetEnrollmentToken()
            << std::endl;
  std::cout << "DM token: " << storage->GetDmToken() << std::endl;
  std::cout << "-------------------------------------------------" << std::endl;

  std::unique_ptr<device_management_storage::CachedPolicyInfo> cached_info =
      GetCachedPolicyInfo(storage);
  if (cached_info) {
    PrintCachedPolicyInfo(*cached_info);
    std::cout << "-------------------------------------------------"
              << std::endl;
  }

  std::cout << "Cached CBCM policies:" << std::endl;
  base::FileEnumerator(storage->policy_cache_folder(), false,
                       base::FileEnumerator::DIRECTORIES)
      .ForEach([](const base::FilePath& policy_path) {
        PrintCachedPolicy(policy_path);
      });

  std::unique_ptr<edm::OmahaSettingsClientProto> omaha_settings =
      GetOmahaPolicySettings();
  if (omaha_settings) {
    std::cout << "-------------------------------------------------"
              << std::endl;
    std::cout << "Google Update CBCM policies:" << std::endl;
    bool has_global_policy = false;
    std::cout << "  Global:" << std::endl;
    if (omaha_settings->has_install_default()) {
      std::cout << "    InstallDefault: " << omaha_settings->install_default()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_update_default()) {
      std::cout << "    UpdateDefault: " << omaha_settings->update_default()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_auto_update_check_period_minutes()) {
      std::cout << "    Auto-update check period minutes: " << std::dec
                << omaha_settings->auto_update_check_period_minutes()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_updates_suppressed()) {
      std::cout << "    Update suppressed: " << std::endl
                << "        Start Hour: "
                << omaha_settings->updates_suppressed().start_hour()
                << std::endl
                << "        Start Minute: "
                << omaha_settings->updates_suppressed().start_minute()
                << std::endl
                << "        Duration Minute: "
                << omaha_settings->updates_suppressed().duration_min()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_proxy_mode()) {
      std::cout << "    Proxy Mode: " << omaha_settings->proxy_mode()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_proxy_pac_url()) {
      std::cout << "    Proxy PacURL: " << omaha_settings->proxy_pac_url()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_proxy_server()) {
      std::cout << "    Proxy Server: " << omaha_settings->proxy_server()
                << std::endl;
      has_global_policy = true;
    }
    if (omaha_settings->has_download_preference()) {
      std::cout << "    DownloadPreference: "
                << omaha_settings->download_preference() << std::endl;
      has_global_policy = true;
    }
    if (!has_global_policy) {
      std::cout << "    (No policy)" << std::endl;
    }

    for (const auto& app_settings : omaha_settings->application_settings()) {
      bool has_policy = false;
      if (app_settings.has_app_guid()) {
        std::cout << "  App : " << app_settings.app_guid();
        if (app_settings.has_bundle_identifier()) {
          std::cout << " (" << app_settings.bundle_identifier() << ")";
        }
        std::cout << std::endl;
      }
      if (app_settings.has_install()) {
        std::cout << "    Install : " << app_settings.install() << std::endl;
        has_policy = true;
      }
      if (app_settings.has_update()) {
        std::cout << "    Update : " << app_settings.update() << std::endl;
        has_policy = true;
      }
      if (app_settings.has_rollback_to_target_version()) {
        std::cout << "    RollbackToTargetVersionAllowed : "
                  << app_settings.rollback_to_target_version() << std::endl;
        has_policy = true;
      }
      if (app_settings.has_target_version_prefix()) {
        std::cout << "    TargetVersionPrefix : "
                  << app_settings.target_version_prefix() << std::endl;
        has_policy = true;
      }
      if (app_settings.has_target_channel()) {
        std::cout << "    TargetChannel : " << app_settings.target_channel()
                  << std::endl;
        has_policy = true;
      }
      if (app_settings.has_gcpw_application_settings()) {
        std::cout << "    DomainsAllowedToLogin: ";
        for (const auto& domain : app_settings.gcpw_application_settings()
                                      .domains_allowed_to_login()) {
          std::cout << domain << ", ";
          has_policy = true;
        }
        std::cout << std::endl;
      }
      if (!has_policy) {
        std::cout << "    (No policy)" << std::endl;
      }
    }
  }
  std::cout << std::endl;
}

}  // namespace updater_policy

UpdaterScope Scope() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(kSystemSwitch)
             ? UpdaterScope::kSystem
             : UpdaterScope::kUser;
}

UpdateService::Priority Priority() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(kBackgroundSwitch)
             ? UpdateService::Priority::kBackground
             : UpdateService::Priority::kForeground;
}

std::string Quoted(const std::string& value) {
  return base::StrCat({"\"", value, "\""});
}

bool OutputInJSONFormat() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(kJSONFormatSwitch);
}

std::string ValueToJSONString(const base::Value& value) {
  std::string value_string;
  return base::JSONWriter::Write(value, &value_string) ? value_string : "";
}

void OnAppStateChanged(const UpdateService::UpdateState& update_state) {
  switch (update_state.state) {
    case UpdateService::UpdateState::State::kCheckingForUpdates:
      std::cout << Quoted(update_state.app_id) << ": checking update... "
                << std::endl;
      break;

    case UpdateService::UpdateState::State::kUpdateAvailable:
      std::cout << Quoted(update_state.app_id)
                << ": update found, next version = "
                << update_state.next_version << std::endl;
      break;

    case UpdateService::UpdateState::State::kDownloading:
      std::cout << Quoted(update_state.app_id)
                << ": downloading update, downloaded bytes: "
                << update_state.downloaded_bytes
                << ", total: " << update_state.total_bytes << std::endl;
      break;

    case UpdateService::UpdateState::State::kInstalling:
      std::cout << Quoted(update_state.app_id)
                << ": installing update, progress at: "
                << update_state.install_progress << std::endl;
      break;

    case UpdateService::UpdateState::State::kUpdated:
      std::cout << Quoted(update_state.app_id)
                << ": updated version = " << update_state.next_version
                << std::endl;
      break;

    case UpdateService::UpdateState::State::kNoUpdate:
      std::cout << Quoted(update_state.app_id) << ": is up-to-date."
                << std::endl;
      break;

    case UpdateService::UpdateState::State::kUpdateError:
      std::cout << Quoted(update_state.app_id) << ": update failed"
                << ", error code: " << update_state.error_code
                << ", extra code: " << update_state.extra_code1 << std::endl;
      break;

    default:
      std::cout << Quoted(update_state.app_id)
                << ": unexpected update state: " << update_state.state
                << std::endl;
      break;
  }
}

void OnUpdateComplete(base::OnceCallback<void(int)> cb,
                      UpdateService::Result result) {
  if (result == UpdateService::Result::kSuccess) {
    std::cout << "App update finished successfully." << std::endl;
    std::move(cb).Run(0);
  } else {
    std::cout << "Failed to update app(s), result = " << result << std::endl;
    std::move(cb).Run(1);
  }
}

class AppState : public base::RefCountedThreadSafe<AppState> {
 public:
  AppState(const std::string& app_id, const std::string& version)
      : app_id_(app_id), current_version_(version) {}

  std::string app_id() const { return app_id_; }
  std::string current_version() const { return current_version_; }
  std::string next_version() const { return next_version_; }
  void set_next_version(const std::string& next_version) {
    next_version_ = next_version;
  }

 protected:
  virtual ~AppState() = default;

 private:
  friend class base::RefCountedThreadSafe<AppState>;

  const std::string app_id_;
  const std::string current_version_;
  std::string next_version_;
};

class UpdaterUtilApp : public App {
 public:
  UpdaterUtilApp() : service_proxy_(CreateUpdateServiceProxy(Scope())) {}

 private:
  ~UpdaterUtilApp() override = default;
  void FirstTaskRun() override;

  void PrintUsage(const std::string& error_message);
  void ListApps();
  void ListUpdate();
  void Update();
  void ListPolicies();
  void ListCBCMPolicies();
  void UnpackCRX();

  void FindApp(const std::string& app_id,
               base::OnceCallback<void(scoped_refptr<AppState>)> callback);
  void DoListUpdate(scoped_refptr<AppState> app_state);
  void DoUpdateApp(scoped_refptr<AppState> app_state);

  scoped_refptr<UpdateService> service_proxy_;
  ScopedIPCSupportWrapper ipc_support_;
};

void UpdaterUtilApp::PrintUsage(const std::string& error_message) {
  if (!error_message.empty()) {
    LOG(ERROR) << error_message;
  }

  std::cout << "Usage: "
            << base::CommandLine::ForCurrentProcess()->GetProgram().BaseName()
            << " [action...] [parameters...]" << R"(
    Actions:
        --update              Update app(s).
        --list-apps           List all registered apps.
        --list-update         List update for an app (skip update install).
        --list-policies       List all currently effective enterprise policies.
        --list-cbcm-policies  List downloaded CBCM policies.
        --unpack=[file]       Verify and unpack a CRX file.
    Action parameters:
        --background          Use background priority.
        --product             ProductID.
        --system              Use the system scope.
        --policy-path         Location of the CBCM policy root path.
        --json                Use JSON as output format where applicable.)"
            << std::endl;
  Shutdown(error_message.empty() ? 0 : 1);
}

void UpdaterUtilApp::ListApps() {
  service_proxy_->GetAppStates(base::BindOnce(
      [](base::OnceCallback<void(int)> cb,
         const std::vector<updater::UpdateService::AppState>& states) {
        if (OutputInJSONFormat()) {
          base::Value::Dict apps;
          for (updater::UpdateService::AppState app : states) {
            apps.Set(app.app_id, base::Value::Dict().Set(
                                     "version", app.version.GetString()));
          }
          std::cout << ValueToJSONString(base::Value(std::move(apps)))
                    << std::endl;
        } else {
          std::cout << "Registered apps : {" << std::endl;
          for (updater::UpdateService::AppState app : states) {
            std::cout << "\t" << Quoted(app.app_id) << " = "
                      << Quoted(app.version.GetString()) << ';' << std::endl;
          }
          std::cout << '}' << std::endl;
        }
        std::move(cb).Run(0);
      },
      base::BindOnce(&UpdaterUtilApp::Shutdown, this)));
}

void UpdaterUtilApp::FindApp(
    const std::string& app_id,
    base::OnceCallback<void(scoped_refptr<AppState>)> callback) {
  service_proxy_->GetAppStates(base::BindOnce(
      [](const std::string& app_id,
         base::OnceCallback<void(scoped_refptr<AppState>)> callback,
         const std::vector<updater::UpdateService::AppState>& states) {
        auto it = std::ranges::find_if(
            states, [&app_id](const updater::UpdateService::AppState& state) {
              return base::EqualsCaseInsensitiveASCII(state.app_id, app_id);
            });
        LOG_IF(ERROR, it == std::end(states))
            << Quoted(app_id) << " is not a registered app.";
        std::move(callback).Run(it == std::end(states)
                                    ? nullptr
                                    : base::MakeRefCounted<AppState>(
                                          app_id, it->version.GetString()));
      },
      app_id, std::move(callback)));
}

void UpdaterUtilApp::ListUpdate() {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();

  const std::string app_id = command_line->GetSwitchValueUTF8(kProductSwitch);
  if (app_id.empty()) {
    PrintUsage("Must specify a product to list update.");
    return;
  }

  FindApp(app_id, base::BindOnce(&UpdaterUtilApp::DoListUpdate, this));
}

void UpdaterUtilApp::DoListUpdate(scoped_refptr<AppState> app_state) {
  if (!app_state) {
    Shutdown(1);
    return;
  }

  service_proxy_->CheckForUpdate(
      app_state->app_id(), Priority(),
      UpdateService::PolicySameVersionUpdate::kNotAllowed,
      /*language=*/{},
      base::BindRepeating(
          [](scoped_refptr<AppState> app_state,
             const UpdateService::UpdateState& update_state) {
            if (update_state.state ==
                UpdateService::UpdateState::State::kUpdateAvailable) {
              app_state->set_next_version(
                  update_state.next_version.GetString());
            }
          },
          app_state),
      base::BindOnce(
          [](scoped_refptr<AppState> app_state,
             base::OnceCallback<void(int)> cb, UpdateService::Result result) {
            if (result == UpdateService::Result::kSuccess) {
              if (OutputInJSONFormat()) {
                base::Value::Dict app;
                app.Set(app_state->app_id(),
                        base::Value::Dict()
                            .Set("CurrentVersion", app_state->current_version())
                            .Set("NextVersion", app_state->next_version()));
                std::cout << ValueToJSONString(base::Value(std::move(app)))
                          << std::endl;
              } else {
                std::cout << Quoted(app_state->app_id()) << " : {" << std::endl
                          << "\tCurrent Version = "
                          << Quoted(app_state->current_version()) << ";"
                          << std::endl
                          << "\tNext Version = "
                          << Quoted(app_state->next_version()) << ";"
                          << std::endl
                          << "}" << std::endl;
              }
              std::move(cb).Run(0);
            }
          },
          app_state, base::BindOnce(&UpdaterUtilApp::Shutdown, this)));
}

void UpdaterUtilApp::Update() {
  const std::string app_id =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueUTF8(
          kProductSwitch);
  if (app_id.empty()) {
    service_proxy_->UpdateAll(
        base::BindRepeating(OnAppStateChanged),
        base::BindOnce(
            [](base::OnceCallback<void(int)> cb, UpdateService::Result result) {
              OnUpdateComplete(std::move(cb), result);
            },
            base::BindOnce(&UpdaterUtilApp::Shutdown, this)));
  } else {
    FindApp(app_id, base::BindOnce(&UpdaterUtilApp::DoUpdateApp, this));
  }
}

void UpdaterUtilApp::DoUpdateApp(scoped_refptr<AppState> app_state) {
  if (!app_state) {
    Shutdown(1);
    return;
  }

  service_proxy_->Update(
      app_state->app_id(), /*install_data_index=*/"", Priority(),
      UpdateService::PolicySameVersionUpdate::kNotAllowed,
      /*language=*/{}, base::BindRepeating(OnAppStateChanged),
      base::BindOnce(
          [](base::OnceCallback<void(int)> cb, UpdateService::Result result) {
            OnUpdateComplete(std::move(cb), result);
          },
          base::BindOnce(&UpdaterUtilApp::Shutdown, this)));
}

void UpdaterUtilApp::ListPolicies() {
  base::ThreadPool::PostTaskAndReply(
      FROM_HERE, {base::MayBlock(), base::WithBaseSyncPrimitives()},
      base::BindOnce([] {
        auto configurator = base::MakeRefCounted<Configurator>(
            CreateGlobalPrefs(Scope()), CreateDefaultExternalConstants(),
            Scope());
        if (OutputInJSONFormat()) {
          std::cout << ValueToJSONString(
                           configurator->GetPolicyService()->GetAllPolicies())
                    << std::endl;
        } else {
          std::cout
              << "Updater policies: "
              << configurator->GetPolicyService()->GetAllPoliciesAsString()
              << std::endl;
        }
      }),
      base::BindOnce(&UpdaterUtilApp::Shutdown, this, 0));
}

void UpdaterUtilApp::ListCBCMPolicies() {
  base::ThreadPool::PostTaskAndReply(
      FROM_HERE, {base::MayBlock(), base::WithBaseSyncPrimitives()},
      base::BindOnce(&updater_policy::PrintCBCMPolicies),
      base::BindOnce(&UpdaterUtilApp::Shutdown, this, 0));
}

void UpdaterUtilApp::UnpackCRX() {
  base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})
      ->PostTask(
          FROM_HERE,
          base::BindOnce(
              &update_client::Unpacker::Unpack, std::vector<uint8_t>(),
              base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
                  kUnpackSwitch),
              base::MakeRefCounted<update_client::InProcessUnzipperFactory>(
                  kSymlinkOption)
                  ->Create(),
              crx_file::VerifierFormat::CRX3,
              base::BindOnce([](const update_client::Unpacker::Result& result) {
                if (result.error == update_client::UnpackerError::kNone) {
                  LOG(INFO) << "Unpacked to " << result.unpack_path
                            << " with public key " << result.public_key;
                } else {
                  LOG(ERROR)
                      << "Unpacking failed: " << static_cast<int>(result.error)
                      << ": " << result.extended_error;
                }
              })
                  .Then(base::BindPostTaskToCurrentDefault(
                      base::BindOnce(&UpdaterUtilApp::Shutdown, this, 0)))));
}

void UpdaterUtilApp::FirstTaskRun() {
  const std::map<std::string, void (UpdaterUtilApp::*)()> commands = {
      {kListAppsSwitch, &UpdaterUtilApp::ListApps},
      {kListUpdateSwitch, &UpdaterUtilApp::ListUpdate},
      {kUpdateSwitch, &UpdaterUtilApp::Update},
      {kListPoliciesSwitch, &UpdaterUtilApp::ListPolicies},
      {kListCBCMPoliciesSwitch, &UpdaterUtilApp::ListCBCMPolicies},
      {kUnpackSwitch, &UpdaterUtilApp::UnpackCRX}};

  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  for (const auto& [switch_name, func] : commands) {
    if (command_line->HasSwitch(switch_name)) {
      (this->*func)();
      return;
    }
  }

  PrintUsage("");
}

int UpdaterUtilMain(int argc, char** argv) {
  base::AtExitManager exit_manager;
  base::CommandLine::Init(argc, argv);
  updater::InitLogging(Scope());
  InitializeThreadPool("updater-util");
  const base::ScopedClosureRunner shutdown_thread_pool(
      base::BindOnce([] { base::ThreadPoolInstance::Get()->Shutdown(); }));
  base::SingleThreadTaskExecutor main_task_executor(base::MessagePumpType::UI);
  return base::MakeRefCounted<UpdaterUtilApp>()->Run();
}

}  // namespace updater::tools

int main(int argc, char** argv) {
  return updater::tools::UpdaterUtilMain(argc, argv);
}