File: support_tool_handler.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; 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 (280 lines) | stat: -rw-r--r-- 10,368 bytes parent folder | download | duplicates (4)
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
// 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 "chrome/browser/support_tool/support_tool_handler.h"

#include <algorithm>
#include <cstddef>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <vector>

#include "base/barrier_closure.h"
#include "base/check.h"
#include "base/check_is_test.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/string_util.h"
#include "base/task/bind_post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/support_tool/data_collector.h"
#include "chrome/browser/support_tool/support_packet_metadata.h"
#include "components/feedback/redaction_tool/pii_types.h"
#include "components/feedback/redaction_tool/redaction_tool.h"
#include "data_collector_utils.h"
#include "third_party/zlib/google/zip.h"

// Zip archieves the contents of `src_path` into `target_path`. Adds ".zip"
// extension to target file path. Returns the path of zip archive on success, an
// empty path otherwise.
base::FilePath ZipOutput(base::FilePath src_path, base::FilePath target_path) {
  base::FilePath zip_path = target_path.AddExtension(FILE_PATH_LITERAL(".zip"));
  if (!zip::Zip(src_path, zip_path, true)) {
    LOG(ERROR) << "Couldn't zip files";
    return base::FilePath();
  }
  return zip_path;
}

// Creates a unique temp directory to store the output files. The caller is
// responsible for deleting the returned directory. Returns an empty FilePath in
// case of an error.
base::FilePath CreateTempDirForOutput() {
  base::ScopedTempDir temp_dir;
  if (!temp_dir.CreateUniqueTempDir()) {
    LOG(ERROR) << "Unable to create temp dir.";
    return base::FilePath{};
  }
  return temp_dir.Take();
}

SupportToolHandler::SupportToolHandler()
    : SupportToolHandler(/*case_id=*/std::string(),
                         /*email_address=*/std::string(),
                         /*issue_description=*/std::string(),
                         std::nullopt) {}

SupportToolHandler::SupportToolHandler(std::string case_id,
                                       std::string email_address,
                                       std::string issue_description,
                                       std::optional<std::string> upload_id)
    : metadata_(case_id, email_address, issue_description, upload_id),
      task_runner_for_redaction_tool_(
          base::ThreadPool::CreateSequencedTaskRunner(
              {base::TaskPriority::USER_VISIBLE,
               base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})),
      redaction_tool_container_(
          base::MakeRefCounted<redaction::RedactionToolContainer>(
              task_runner_for_redaction_tool_,
              nullptr)) {}

SupportToolHandler::~SupportToolHandler() {
  CleanUp();
}

void SupportToolHandler::CleanUp() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Clean the temporary directory in a worker thread if it hasn't been removed
  // yet.
  if (!temp_dir_.empty()) {
    base::ThreadPool::PostTask(
        FROM_HERE,
        {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
         base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
        base::GetDeletePathRecursivelyCallback(std::move(temp_dir_)));
    temp_dir_.clear();
  }
}

const std::string& SupportToolHandler::GetCaseId() {
  return metadata_.GetCaseId();
}

const base::Time& SupportToolHandler::GetDataCollectionTimestamp() {
  return data_collection_timestamp_;
}

void SupportToolHandler::AddDataCollector(
    std::unique_ptr<DataCollector> collector) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(collector);
  data_collectors_.emplace_back(std::move(collector));
}

const std::vector<std::unique_ptr<DataCollector>>&
SupportToolHandler::GetDataCollectorsForTesting() {
  CHECK_IS_TEST();
  return data_collectors_;
}

void SupportToolHandler::CollectSupportData(
    SupportToolDataCollectedCallback on_data_collection_done_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!on_data_collection_done_callback.is_null());
  DCHECK(!data_collectors_.empty());

  on_data_collection_done_callback_ =
      std::move(on_data_collection_done_callback);

  base::RepeatingClosure collect_data_barrier_closure = base::BarrierClosure(
      data_collectors_.size(),
      base::BindOnce(&SupportToolHandler::OnAllDataCollected,
                     weak_ptr_factory_.GetWeakPtr()));

  data_collection_timestamp_ = base::Time::NowFromSystemTime();

  for (auto& data_collector : data_collectors_) {
    // DataCollectors will use `redaction_tool_container_` on
    // `task_runner_for_redaction_tool_` to redact PII from the collected logs.
    // All DataCollectors will use the same RedactionTool instance on the same
    // task runner as we need to replace the same PII data with the same
    // place-holder strings (that are stored in RedactionTool instance's data
    // member) in all collected logs to avoid confusing the reader.
    data_collector->CollectDataAndDetectPII(
        base::BindOnce(&SupportToolHandler::OnDataCollected,
                       weak_ptr_factory_.GetWeakPtr(),
                       collect_data_barrier_closure),
        task_runner_for_redaction_tool_, redaction_tool_container_);
  }
}

void SupportToolHandler::OnDataCollected(
    base::RepeatingClosure barrier_closure,
    std::optional<SupportToolError> error) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (error) {
    collected_errors_.insert(error.value());
  }
  std::move(barrier_closure).Run();
}

void SupportToolHandler::AddDetectedPII(const PIIMap& pii_map) {
  MergePIIMaps(detected_pii_, pii_map);
}

void SupportToolHandler::OnAllDataCollected() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  for (auto& data_collector : data_collectors_) {
    AddDetectedPII(data_collector->GetDetectedPII());
  }

  metadata_.InsertErrors(collected_errors_);

  metadata_.PopulateMetadataContents(
      data_collection_timestamp_, data_collectors_,
      base::BindOnce(&SupportToolHandler::OnMetadataContentsPopulated,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SupportToolHandler::OnMetadataContentsPopulated() {
  AddDetectedPII(metadata_.GetPII());
  std::move(on_data_collection_done_callback_)
      .Run(detected_pii_, collected_errors_);
}

void SupportToolHandler::ExportCollectedData(
    std::set<redaction::PIIType> pii_types_to_keep,
    base::FilePath target_path,
    SupportToolDataExportedCallback on_data_exported_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Clear the set of previously collected errors.
  collected_errors_.clear();

  on_data_export_done_callback_ = std::move(on_data_exported_callback);

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()}, base::BindOnce(&CreateTempDirForOutput),
      base::BindOnce(&SupportToolHandler::ExportIntoTempDir,
                     weak_ptr_factory_.GetWeakPtr(), pii_types_to_keep,
                     target_path));
}

void SupportToolHandler::ExportIntoTempDir(
    std::set<redaction::PIIType> pii_types_to_keep,
    base::FilePath target_path,
    base::FilePath tmp_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (tmp_path.empty()) {
    collected_errors_.insert(
        {SupportToolErrorCode::kDataExportError,
         "Failed to create temporary directory for output."});
    std::move(on_data_export_done_callback_)
        .Run(base::FilePath(), collected_errors_);
    return;
  }

  temp_dir_ = tmp_path;

  base::RepeatingClosure export_data_barrier_closure = base::BarrierClosure(
      data_collectors_.size(),
      base::BindOnce(&SupportToolHandler::OnAllDataCollectorsDoneExporting,
                     weak_ptr_factory_.GetWeakPtr(), temp_dir_, target_path,
                     pii_types_to_keep));

  for (auto& data_collector : data_collectors_) {
    data_collector->ExportCollectedDataWithPII(
        pii_types_to_keep, temp_dir_, task_runner_for_redaction_tool_,
        redaction_tool_container_,
        base::BindOnce(&SupportToolHandler::OnDataCollectorDoneExporting,
                       weak_ptr_factory_.GetWeakPtr(),
                       export_data_barrier_closure));
  }
}

void SupportToolHandler::OnDataCollectorDoneExporting(
    base::RepeatingClosure barrier_closure,
    std::optional<SupportToolError> error) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (error) {
    collected_errors_.insert(error.value());
  }
  std::move(barrier_closure).Run();
}

void SupportToolHandler::OnAllDataCollectorsDoneExporting(
    base::FilePath tmp_path,
    base::FilePath target_path,
    std::set<redaction::PIIType> pii_types_to_keep) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  metadata_.InsertErrors(collected_errors_);
  metadata_.WriteMetadataFile(
      tmp_path, pii_types_to_keep,
      base::BindOnce(&SupportToolHandler::OnMetadataFileWritten,
                     weak_ptr_factory_.GetWeakPtr(), tmp_path, target_path));
}

void SupportToolHandler::OnMetadataFileWritten(base::FilePath tmp_path,
                                               base::FilePath target_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Archive the contents in the `tmp_path` into `target_path` in a zip file.
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock()},
      base::BindOnce(&ZipOutput, tmp_path, target_path),
      base::BindOnce(&SupportToolHandler::OnDataExportDone,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SupportToolHandler::OnDataExportDone(base::FilePath exported_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Clean-up the temporary directory after exporting the data.
  CleanUp();
  if (exported_path.empty()) {
    collected_errors_.insert({SupportToolErrorCode::kDataExportError,
                              "Failed to archive the output files."});
  }
  std::move(on_data_export_done_callback_)
      .Run(exported_path, collected_errors_);
}