File: devtools_file_helper.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 (544 lines) | stat: -rw-r--r-- 20,833 bytes parent folder | download | duplicates (5)
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
// 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.

#include "chrome/browser/devtools/devtools_file_helper.h"

#include <set>
#include <vector>

#include "base/base64.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/hash/md5.h"
#include "base/json/values_util.h"
#include "base/lazy_instance.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/devtools/devtools_file_watcher.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/download_manager.h"
#include "content/public/common/content_client.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"
#include "url/origin.h"

using content::BrowserThread;
using std::set;

namespace {

static const char kAutomaticFileSystemType[] = "automatic";
static const char kDefaultFileSystemType[] = "";

static const char kIllegalPath[] = "<illegal path>";
static const char kIllegalType[] = "<illegal type>";
static const char kPermissionDenied[] = "<permission denied>";
static const char kSelectionCancelled[] = "<selection cancelled>";

base::LazyInstance<base::FilePath>::Leaky g_last_save_path =
    LAZY_INSTANCE_INITIALIZER;

void WriteToFile(const base::FilePath& path,
                 const std::string& content,
                 bool is_base64) {
  DCHECK(!path.empty());

  if (!is_base64) {
    base::WriteFile(path, content);
    return;
  }

  const std::optional<std::vector<uint8_t>> decoded_content =
      base::Base64Decode(content);
  if (decoded_content) {
    base::WriteFile(path, decoded_content.value());
  } else {
    LOG(ERROR) << "Invalid base64. Not writing " << path;
  }
}

void AppendToFile(const base::FilePath& path, const std::string& content) {
  DCHECK(!path.empty());

  base::AppendToFile(path, content);
}

}  // namespace

DevToolsFileHelper::FileSystem::FileSystem() = default;

DevToolsFileHelper::FileSystem::~FileSystem() = default;

DevToolsFileHelper::FileSystem::FileSystem(const FileSystem& other) = default;

DevToolsFileHelper::FileSystem::FileSystem(const std::string& type,
                                           const std::string& file_system_name,
                                           const std::string& root_url,
                                           const std::string& file_system_path)
    : type(type),
      file_system_name(file_system_name),
      root_url(root_url),
      file_system_path(file_system_path) {}

DevToolsFileHelper::Storage::~Storage() = default;

DevToolsFileHelper::DevToolsFileHelper(Profile* profile,
                                       Delegate* delegate,
                                       Storage* storage)
    : profile_(profile),
      delegate_(delegate),
      storage_(storage),
      file_task_runner_(
          base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) {
  pref_change_registrar_.Init(profile_->GetPrefs());
}

DevToolsFileHelper::~DevToolsFileHelper() = default;

void DevToolsFileHelper::Save(const std::string& url,
                              const std::string& content,
                              bool save_as,
                              bool is_base64,
                              SelectFileCallback select_file_callback,
                              SaveCallback save_callback,
                              CanceledCallback canceled_callback) {
  auto it = saved_files_.find(url);
  if (it != saved_files_.end() && !save_as) {
    SaveToFileSelected(url, content, is_base64, std::move(save_callback),
                       it->second);
    return;
  }

  const base::Value::Dict& file_map =
      profile_->GetPrefs()->GetDict(prefs::kDevToolsEditedFiles);
  base::FilePath initial_path;

  if (const base::Value* path_value = file_map.Find(base::MD5String(url))) {
    std::optional<base::FilePath> path = base::ValueToFilePath(*path_value);
    if (path) {
      initial_path = std::move(*path);
    }
  }

  if (initial_path.empty()) {
    GURL gurl(url);
    std::string suggested_file_name;
    if (gurl.is_valid()) {
      url::RawCanonOutputW<1024> unescaped_content;
      std::string escaped_content = gurl.ExtractFileName();
      url::DecodeURLEscapeSequences(escaped_content,
                                    url::DecodeURLMode::kUTF8OrIsomorphic,
                                    &unescaped_content);
      // TODO(crbug.com/40839171): Due to filename encoding on Windows we can't
      // expect to always be able to convert to UTF8 and back
      std::string unescaped_content_string =
          base::UTF16ToUTF8(unescaped_content.view());
      suggested_file_name = unescaped_content_string;
    } else {
      suggested_file_name = url;
    }
    // TODO(crbug.com/40839171): Truncate a UTF8 string in a better way
    if (suggested_file_name.length() > 64) {
      suggested_file_name = suggested_file_name.substr(0, 64);
    }
    // TODO(crbug.com/40839171): Ensure suggested_file_name is an ASCII string
    if (!g_last_save_path.Pointer()->empty()) {
      initial_path = g_last_save_path.Pointer()->DirName().AppendASCII(
          suggested_file_name);
    } else {
      base::FilePath download_path =
          DownloadPrefs::FromDownloadManager(profile_->GetDownloadManager())
              ->DownloadPath();
      initial_path = download_path.AppendASCII(suggested_file_name);
    }
  }

  std::move(select_file_callback)
      .Run(base::BindOnce(&DevToolsFileHelper::SaveToFileSelected,
                          weak_factory_.GetWeakPtr(), url, content, is_base64,
                          std::move(save_callback)),
           std::move(canceled_callback), initial_path);
}

void DevToolsFileHelper::Append(const std::string& url,
                                const std::string& content,
                                base::OnceClosure callback) {
  auto it = saved_files_.find(url);
  if (it == saved_files_.end()) {
    return;
  }
  std::move(callback).Run();
  file_task_runner_->PostTask(FROM_HERE,
                              BindOnce(&AppendToFile, it->second, content));
}

void DevToolsFileHelper::SaveToFileSelected(const std::string& url,
                                            const std::string& content,
                                            bool is_base64,
                                            SaveCallback callback,
                                            const base::FilePath& path) {
  *g_last_save_path.Pointer() = path;
  saved_files_[url] = path;

  ScopedDictPrefUpdate update(profile_->GetPrefs(),
                              prefs::kDevToolsEditedFiles);
  base::Value::Dict& files_map = update.Get();
  files_map.Set(base::MD5String(url), base::FilePathToValue(path));

  std::string file_system_path = path.AsUTF8Unsafe();
  // Run 'SaveCallback' only once we have actually written the file, but
  // run it on the current task runner.
  scoped_refptr<base::SequencedTaskRunner> current_task_runner =
      base::SequencedTaskRunner::GetCurrentDefault();
  file_task_runner_->PostTask(
      FROM_HERE, BindOnce(&WriteToFile, path, content, is_base64)
                     .Then(base::BindPostTask(
                         current_task_runner,
                         BindOnce(std::move(callback), file_system_path))));
}

void DevToolsFileHelper::AddFileSystem(
    const std::string& type,
    SelectFileCallback select_file_callback,
    const HandlePermissionsCallback& handle_permissions_callback) {
  // Make sure the |type| is not a valid UUID. These are reserved for automatic
  // file systems.
  if (type == kAutomaticFileSystemType ||
      base::Uuid::ParseCaseInsensitive(type).is_valid()) {
    FailedToAddFileSystem(kIllegalType);
    return;
  }

  std::move(select_file_callback)
      .Run(base::BindOnce(&DevToolsFileHelper::InnerAddFileSystem,
                          weak_factory_.GetWeakPtr(),
                          handle_permissions_callback, type),
           base::BindOnce(&DevToolsFileHelper::FailedToAddFileSystem,
                          weak_factory_.GetWeakPtr(), kSelectionCancelled),
           base::FilePath());
}

void DevToolsFileHelper::UpgradeDraggedFileSystemPermissions(
    const std::string& file_system_url,
    const HandlePermissionsCallback& handle_permissions_callback) {
  auto file_system_paths =
      storage_->GetDraggedFileSystemPaths(GURL(file_system_url));
  for (const auto& file_system_path : file_system_paths) {
    InnerAddFileSystem(handle_permissions_callback, kDefaultFileSystemType,
                       file_system_path);
  }
}

void DevToolsFileHelper::ConnectAutomaticFileSystem(
    const std::string& file_system_path,
    const base::Uuid& file_system_uuid,
    bool add_if_missing,
    const HandlePermissionsCallback& handle_permissions_callback,
    ConnectCallback connect_callback) {
  DCHECK(file_system_uuid.is_valid());

  // Make sure that |file_system_path| is a valid absolute path.
  base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path);
  if (!path.IsAbsolute()) {
    LOG(ERROR) << "Rejected automatic file system " << file_system_path
               << " with UUID " << file_system_uuid << " because it's not"
               << " a valid absolute path.";
    std::move(connect_callback).Run(false);
    FailedToAddFileSystem(kIllegalPath);
    return;
  }

  // Check if the automatic file system is already known, and potentially
  // already connected (in this session).
  if (IsUserConfirmedAutomaticFileSystem(file_system_path, file_system_uuid)) {
    if (connected_automatic_file_systems_.emplace(file_system_path).second) {
      // The |file_system_path| is known, but was just connected now
      // (within this session).
      VLOG(1) << "Automatic file system " << file_system_path << " with UUID "
              << file_system_uuid << " was found in the profile, and will be "
              << "automatically connected now.";
      connected_automatic_file_systems_.emplace(file_system_path);
      UpdateFileSystemPathsOnUI();
    } else {
      // The |file_system_path| was already connected.
      VLOG(1) << "Automatic file system " << file_system_path << " with UUID "
              << file_system_uuid << " was already connected.";
    }
    std::move(connect_callback).Run(true);
    return;
  }

  if (!add_if_missing) {
    VLOG(1) << "Not adding automatic file system " << file_system_path
            << " with UUID " << file_system_uuid << ".";
    std::move(connect_callback).Run(false);
    return;
  }

  // Ensure that the |path| refers to an existing directory first (since this
  // is a blocking call, we need to perform this operation asynchronously).
  file_task_runner_->PostTaskAndReplyWithResult(
      FROM_HERE, BindOnce(&base::DirectoryExists, path),
      BindOnce(&DevToolsFileHelper::ConnectMissingAutomaticFileSystem,
               weak_factory_.GetWeakPtr(), std::move(file_system_path),
               std::move(file_system_uuid),
               std::move(handle_permissions_callback),
               std::move(connect_callback)));
}

void DevToolsFileHelper::ConnectMissingAutomaticFileSystem(
    const std::string& file_system_path,
    const base::Uuid& file_system_uuid,
    const HandlePermissionsCallback& handle_permissions_callback,
    ConnectCallback connect_callback,
    bool directory_exists) {
  if (!directory_exists) {
    LOG(ERROR) << "Rejected automatic file system " << file_system_path
               << " with UUID " << file_system_uuid << " because that"
               << "directory does not exist.";
    std::move(connect_callback).Run(false);
    FailedToAddFileSystem(kIllegalPath);
    return;
  }

  if (IsFileSystemAdded(file_system_path)) {
    RemoveFileSystem(file_system_path);
  }

  std::u16string message =
      l10n_util::GetStringFUTF16(IDS_DEV_TOOLS_CONFIRM_ADD_FILE_SYSTEM_MESSAGE,
                                 base::UTF8ToUTF16(file_system_path));
  handle_permissions_callback.Run(
      file_system_path, message,
      BindOnce(&DevToolsFileHelper::ConnectUserConfirmedAutomaticFileSystem,
               weak_factory_.GetWeakPtr(), std::move(connect_callback),
               file_system_path, file_system_uuid));
}

void DevToolsFileHelper::ConnectUserConfirmedAutomaticFileSystem(
    ConnectCallback connect_callback,
    const std::string& file_system_path,
    const base::Uuid& file_system_uuid,
    bool allowed) {
  VLOG(1) << "User " << (allowed ? "allowed" : "denied")
          << " adding automatic file system " << file_system_path
          << " with UUID " << file_system_uuid << ".";
  if (allowed) {
    connected_automatic_file_systems_.emplace(file_system_path);
  }

  auto path = base::FilePath::FromUTF8Unsafe(file_system_path);
  auto type = file_system_uuid.AsLowercaseString();
  AddUserConfirmedFileSystem(type, path, allowed);

  std::move(connect_callback).Run(allowed);
}

bool DevToolsFileHelper::IsUserConfirmedAutomaticFileSystem(
    const std::string& file_system_path,
    const base::Uuid& file_system_uuid) const {
  DCHECK(file_system_uuid.is_valid());
  const base::Value::Dict& file_system_paths_value =
      profile_->GetPrefs()->GetDict(prefs::kDevToolsFileSystemPaths);
  const base::Value* value = file_system_paths_value.Find(file_system_path);
  if (value == nullptr || !value->is_string()) {
    return false;
  }
  return value->GetString() == file_system_uuid.AsLowercaseString();
}

void DevToolsFileHelper::DisconnectAutomaticFileSystem(
    const std::string& file_system_path) {
  if (connected_automatic_file_systems_.erase(file_system_path) == 1) {
    VLOG(1) << "Disconnected automatic file system " << file_system_path << ".";
    UpdateFileSystemPathsOnUI();
  }
}

void DevToolsFileHelper::InnerAddFileSystem(
    const HandlePermissionsCallback& handle_permissions_callback,
    const std::string& type,
    const base::FilePath& path) {
  std::string file_system_path = path.AsUTF8Unsafe();

  if (IsFileSystemAdded(file_system_path)) {
    RemoveFileSystem(file_system_path);
  }

  std::string path_display_name = path.AsEndingWithSeparator().AsUTF8Unsafe();
  std::u16string message =
      l10n_util::GetStringFUTF16(IDS_DEV_TOOLS_CONFIRM_ADD_FILE_SYSTEM_MESSAGE,
                                 base::UTF8ToUTF16(path_display_name));
  handle_permissions_callback.Run(
      file_system_path, message,
      BindOnce(&DevToolsFileHelper::AddUserConfirmedFileSystem,
               weak_factory_.GetWeakPtr(), type, path));
}

void DevToolsFileHelper::AddUserConfirmedFileSystem(const std::string& type,
                                                    const base::FilePath& path,
                                                    bool allowed) {
  if (!allowed) {
    FailedToAddFileSystem(kPermissionDenied);
    return;
  }

  ScopedDictPrefUpdate update(profile_->GetPrefs(),
                              prefs::kDevToolsFileSystemPaths);
  base::Value::Dict& file_systems_paths_value = update.Get();
  file_systems_paths_value.Set(path.AsUTF8Unsafe(), type);
}

void DevToolsFileHelper::FailedToAddFileSystem(const std::string& error) {
  delegate_->FileSystemAdded(error, nullptr);
}

namespace {

void RunOnUIThread(base::OnceClosure callback) {
  content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(callback));
}

}  // namespace

std::vector<DevToolsFileHelper::FileSystem>
DevToolsFileHelper::GetFileSystems() {
  file_system_paths_ = GetActiveFileSystemPaths();
  std::vector<FileSystem> file_systems;
  if (!file_watcher_) {
    file_watcher_.reset(new DevToolsFileWatcher(
        base::BindRepeating(&DevToolsFileHelper::FilePathsChanged,
                            weak_factory_.GetWeakPtr()),
        base::SequencedTaskRunner::GetCurrentDefault()));
    auto change_handler_on_ui =
        base::BindRepeating(&DevToolsFileHelper::UpdateFileSystemPathsOnUI,
                            weak_factory_.GetWeakPtr());
    pref_change_registrar_.Add(
        prefs::kDevToolsFileSystemPaths,
        base::BindRepeating(RunOnUIThread, change_handler_on_ui));
  }
  for (const auto& file_system_path : file_system_paths_) {
    auto path = base::FilePath::FromUTF8Unsafe(file_system_path.first);
    auto file_system =
        storage_->RegisterFileSystem(path, file_system_path.second);
    file_systems.push_back(file_system);
    file_watcher_->AddWatch(std::move(path));
  }
  return file_systems;
}

void DevToolsFileHelper::RemoveFileSystem(const std::string& file_system_path) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto path = base::FilePath::FromUTF8Unsafe(file_system_path);

  if (connected_automatic_file_systems_.erase(file_system_path) == 1) {
    VLOG(1) << "Disconnected automatic file system " << file_system_path
            << " (prior to removal).";
  }

  ScopedDictPrefUpdate update(profile_->GetPrefs(),
                              prefs::kDevToolsFileSystemPaths);
  base::Value::Dict& file_systems_paths_value = update.Get();
  file_systems_paths_value.Remove(file_system_path);
}

bool DevToolsFileHelper::IsFileSystemAdded(
    const std::string& file_system_path) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  return file_system_paths_.contains(file_system_path);
}

void DevToolsFileHelper::OnOpenItemComplete(
    const base::FilePath& path,
    platform_util::OpenOperationResult result) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (result == platform_util::OPEN_FAILED_INVALID_TYPE) {
    platform_util::ShowItemInFolder(profile_, path);
  }
}

void DevToolsFileHelper::ShowItemInFolder(const std::string& file_system_path) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (file_system_path.empty()) {
    return;
  }
  base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path);
  platform_util::OpenItem(
      profile_, path, platform_util::OPEN_FOLDER,
      base::BindOnce(&DevToolsFileHelper::OnOpenItemComplete,
                     weak_factory_.GetWeakPtr(), path));
}

void DevToolsFileHelper::UpdateFileSystemPathsOnUI() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  PathToType remaining;
  remaining.swap(file_system_paths_);
  DCHECK(file_watcher_.get());

  for (const auto& file_system_path : GetActiveFileSystemPaths()) {
    if (remaining.find(file_system_path.first) == remaining.end()) {
      auto path = base::FilePath::FromUTF8Unsafe(file_system_path.first);
      auto file_system =
          storage_->RegisterFileSystem(path, file_system_path.second);
      delegate_->FileSystemAdded(std::string(), &file_system);
      file_watcher_->AddWatch(std::move(path));
    } else {
      remaining.erase(file_system_path.first);
    }
    file_system_paths_[file_system_path.first] = file_system_path.second;
  }

  for (const auto& file_system : remaining) {
    delegate_->FileSystemRemoved(file_system.first);
    base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system.first);
    storage_->UnregisterFileSystem(path);
    file_watcher_->RemoveWatch(std::move(path));
  }
}

void DevToolsFileHelper::FilePathsChanged(
    const std::vector<std::string>& changed_paths,
    const std::vector<std::string>& added_paths,
    const std::vector<std::string>& removed_paths) {
  delegate_->FilePathsChanged(changed_paths, added_paths, removed_paths);
}

DevToolsFileHelper::PathToType DevToolsFileHelper::GetActiveFileSystemPaths() {
  const base::Value::Dict& file_systems_paths_value =
      profile_->GetPrefs()->GetDict(prefs::kDevToolsFileSystemPaths);
  PathToType result;
  for (auto pair : file_systems_paths_value) {
    const std::string& path = pair.first;
    std::string type;
    if (pair.second.is_string()) {
      type = pair.second.GetString();
    }
    // If the |type| is a valid UUID, it signifies an automatic file
    // system. We only report the subset of automatic file systems that
    // are (currently) connected (within this session). And we report them
    // with type "automatic".
    if (base::Uuid::ParseLowercase(type).is_valid()) {
      if (!connected_automatic_file_systems_.contains(path)) {
        continue;
      }
      type = kAutomaticFileSystemType;
    }
    result[path] = type;
  }
  return result;
}