File: file_system_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 (436 lines) | stat: -rw-r--r-- 14,954 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

#include "storage/common/file_system/file_system_util.h"

#include <stddef.h>

#include <algorithm>

#include "base/check.h"
#include "base/notreached.h"
#include "base/strings/escape.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "build/build_config.h"
#include "net/base/net_errors.h"
#include "storage/common/database/database_identifier.h"
#include "url/gurl.h"

namespace storage {

const char kPersistentDir[] = "/persistent";
const char kTemporaryDir[] = "/temporary";
const char kIsolatedDir[] = "/isolated";
const char kExternalDir[] = "/external";
const char kTestDir[] = "/test";

const base::FilePath::CharType VirtualPath::kRoot[] = FILE_PATH_LITERAL("/");
const base::FilePath::CharType VirtualPath::kSeparator = FILE_PATH_LITERAL('/');

// TODO(ericu): Consider removing support for '\', even on Windows, if possible.
// There's a lot of test code that will need reworking, and we may have trouble
// with base::FilePath elsewhere [e.g. DirName and other methods may also need
// replacement].
base::FilePath VirtualPath::BaseName(const base::FilePath& virtual_path) {
  base::FilePath::StringType path = virtual_path.value();

  // Keep everything after the final separator, but if the pathname is only
  // one character and it's a separator, leave it alone.
  while (path.size() > 1 && base::FilePath::IsSeparator(path.back()))
    path.resize(path.size() - 1);
  base::FilePath::StringType::size_type last_separator =
      path.find_last_of(base::FilePath::kSeparators);
  if (last_separator != base::FilePath::StringType::npos &&
      last_separator < path.size() - 1)
    path.erase(0, last_separator + 1);

  return base::FilePath(path);
}

base::FilePath VirtualPath::DirName(const base::FilePath& virtual_path) {
  using StringType = base::FilePath::StringType;
  StringType path = virtual_path.value();

  // The logic below is taken from that of base::FilePath::DirName, except
  // that this version never cares about '//' or drive-letters even on win32.

  // Strip trailing separators.
  while (path.size() > 1 && base::FilePath::IsSeparator(path.back()))
    path.resize(path.size() - 1);

  StringType::size_type last_separator =
      path.find_last_of(base::FilePath::kSeparators);
  if (last_separator == StringType::npos) {
    // path_ is in the current directory.
    return base::FilePath(base::FilePath::kCurrentDirectory);
  }
  if (last_separator == 0) {
    // path_ is in the root directory.
    return base::FilePath(path.substr(0, 1));
  }
  // path_ is somewhere else, trim the basename.
  path.resize(last_separator);

  // Strip trailing separators.
  while (path.size() > 1 && base::FilePath::IsSeparator(path.back()))
    path.resize(path.size() - 1);

  if (path.empty())
    return base::FilePath(base::FilePath::kCurrentDirectory);

  return base::FilePath(path);
}

std::vector<base::FilePath::StringType> VirtualPath::GetComponents(
    const base::FilePath& path) {
  using StringType = base::FilePath::StringType;

  std::vector<StringType> components;
  if (path.value().empty())
    return components;

  StringType::size_type begin = 0, end = 0;
  while (begin < path.value().length() && end != StringType::npos) {
    end = path.value().find_first_of(base::FilePath::kSeparators, begin);
    StringType component = path.value().substr(
        begin, end == StringType::npos ? StringType::npos : end - begin);
    if (!component.empty() && component != base::FilePath::kCurrentDirectory)
      components.push_back(component);
    begin = end + 1;
  }
  return components;
}

std::vector<std::string> VirtualPath::GetComponentsUTF8Unsafe(
    const base::FilePath& path) {
  std::vector<base::FilePath::StringType> stringtype_components =
      VirtualPath::GetComponents(path);
  std::vector<std::string> components;
  components.reserve(stringtype_components.size());
  for (const auto& component : stringtype_components)
    components.push_back(base::FilePath(component).AsUTF8Unsafe());
  return components;
}

base::FilePath::StringType VirtualPath::GetNormalizedFilePath(
    const base::FilePath& path) {
  base::FilePath::StringType normalized_path = path.value();
  const size_t num_separators =
      base::FilePath::StringType(base::FilePath::kSeparators).length();
  for (size_t i = 0; i < num_separators; ++i) {
    std::replace(normalized_path.begin(), normalized_path.end(),
                 base::FilePath::kSeparators[i], kSeparator);
  }

  return (IsAbsolute(normalized_path))
             ? normalized_path
             : base::FilePath::StringType(kRoot) + normalized_path;
}

bool VirtualPath::IsAbsolute(const base::FilePath::StringType& path) {
  return base::StartsWith(path, kRoot, base::CompareCase::SENSITIVE);
}

bool VirtualPath::IsRootPath(const base::FilePath& path) {
  std::vector<base::FilePath::StringType> components =
      VirtualPath::GetComponents(path);
  return (path.empty() || components.empty() ||
          (components.size() == 1 && components[0] == VirtualPath::kRoot));
}

bool ParseFileSystemSchemeURL(const GURL& url,
                              GURL* origin_url,
                              FileSystemType* type,
                              base::FilePath* virtual_path) {
  GURL origin;
  FileSystemType file_system_type = kFileSystemTypeUnknown;

  if (!url.is_valid() || !url.SchemeIsFileSystem())
    return false;

  const struct {
    FileSystemType type;
    const char* dir;
  } kValidTypes[] = {
      {kFileSystemTypePersistent, kPersistentDir},
      {kFileSystemTypeTemporary, kTemporaryDir},
      {kFileSystemTypeIsolated, kIsolatedDir},
      {kFileSystemTypeExternal, kExternalDir},
      {kFileSystemTypeTest, kTestDir},
  };

  // A path of the inner_url contains only mount type part (e.g. "/temporary").
  DCHECK(url.inner_url());
  std::string inner_path = url.inner_url()->path();
  for (const auto& valid_type : kValidTypes) {
    if (inner_path == valid_type.dir) {
      file_system_type = valid_type.type;
      break;
    }
  }

  if (file_system_type == kFileSystemTypeUnknown)
    return false;

  std::string path = base::UnescapeBinaryURLComponent(url.path_piece());

  // Ensure the path is relative.
  while (!path.empty() && path[0] == '/')
    path.erase(0, 1);

  base::FilePath converted_path = base::FilePath::FromUTF8Unsafe(path);

  // All parent references should have been resolved in the renderer.
  if (converted_path.ReferencesParent())
    return false;

  if (origin_url)
    *origin_url = url.DeprecatedGetOriginAsURL();
  if (type)
    *type = file_system_type;
  if (virtual_path)
    *virtual_path =
        converted_path.NormalizePathSeparators().StripTrailingSeparators();

  return true;
}

GURL GetFileSystemRootURI(const GURL& origin_url, FileSystemType type) {
  // origin_url is based on a security origin, so http://foo.com or file:///
  // instead of the corresponding filesystem URL.
  DCHECK(!origin_url.SchemeIsFileSystem());

  std::string url = "filesystem:" + origin_url.GetWithEmptyPath().spec();
  switch (type) {
    case kFileSystemTypeTemporary:
      url += (kTemporaryDir + 1);  // We don't want the leading slash.
      return GURL(url + "/");
    case kFileSystemTypePersistent:
      url += (kPersistentDir + 1);  // We don't want the leading slash.
      return GURL(url + "/");
    case kFileSystemTypeExternal:
      url += (kExternalDir + 1);  // We don't want the leading slash.
      return GURL(url + "/");
    case kFileSystemTypeIsolated:
      url += (kIsolatedDir + 1);  // We don't want the leading slash.
      return GURL(url + "/");
    case kFileSystemTypeTest:
      url += (kTestDir + 1);  // We don't want the leading slash.
      return GURL(url + "/");
      // Internal types are always pointed via isolated or external URLs.
    default:
      NOTREACHED();
  }
}

std::string GetFileSystemName(const GURL& origin_url, FileSystemType type) {
  std::string origin_identifier = storage::GetIdentifierFromOrigin(origin_url);
  std::string type_string = GetFileSystemTypeString(type);
  DCHECK(!type_string.empty());
  return origin_identifier + ":" + type_string;
}

std::string GetFileSystemTypeString(FileSystemType type) {
  switch (type) {
    case kFileSystemTypeTemporary:
      return "Temporary";
    case kFileSystemTypePersistent:
      return "Persistent";
    case kFileSystemTypeIsolated:
      return "Isolated";
    case kFileSystemTypeExternal:
      return "External";
    case kFileSystemTypeTest:
      return "Test";
    case kFileSystemTypeLocal:
      return "Local";
    case kFileSystemTypeDragged:
      return "Dragged";
    case kFileSystemTypeLocalMedia:
      return "LocalMedia";
    case kFileSystemTypeDeviceMedia:
      return "DeviceMedia";
    case kFileSystemTypeSyncable:
    case kFileSystemTypeSyncableForInternalSync:
      return "Syncable";
    case kFileSystemTypeLocalForPlatformApp:
      return "LocalForPlatformApp";
    case kFileSystemTypeForTransientFile:
      return "TransientFile";
    case kFileSystemTypeProvided:
      return "Provided";
    case kFileSystemTypeDeviceMediaAsFileStorage:
      return "DeviceMediaStorage";
    case kFileSystemTypeArcContent:
      return "ArcContent";
    case kFileSystemTypeArcDocumentsProvider:
      return "ArcDocumentsProvider";
    case kFileSystemTypeDriveFs:
      return "DriveFs";
    case kFileSystemTypeSmbFs:
      return "SmbFs";
    case kFileSystemTypeFuseBox:
      return "FuseBox";
    case kFileSystemInternalTypeEnumStart:
    case kFileSystemInternalTypeEnumEnd:
      NOTREACHED();
    case kFileSystemTypeUnknown:
      return "Unknown";
  }
  NOTREACHED();
}

std::string FilePathToString(const base::FilePath& file_path) {
  // TODO(pkasting): Probably this should use AsUTF8Unsafe() across platforms.
#if BUILDFLAG(IS_WIN)
  return file_path.AsUTF8Unsafe();
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  return file_path.value();
#endif
}

base::FilePath StringToFilePath(const std::string& file_path_string) {
  // TODO(pkasting): Probably this should use FromUTF8Unsafe() across platforms.
#if BUILDFLAG(IS_WIN)
  return base::FilePath::FromUTF8Unsafe(file_path_string);
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  return base::FilePath(file_path_string);
#endif
}

bool GetFileSystemPublicType(const std::string& type_string,
                             blink::WebFileSystemType* type) {
  DCHECK(type);
  if (type_string == "Temporary") {
    *type = blink::kWebFileSystemTypeTemporary;
    return true;
  }
  if (type_string == "Persistent") {
    *type = blink::kWebFileSystemTypePersistent;
    return true;
  }
  if (type_string == "Isolated") {
    *type = blink::kWebFileSystemTypeIsolated;
    return true;
  }
  if (type_string == "External") {
    *type = blink::kWebFileSystemTypeExternal;
    return true;
  }
  NOTREACHED();
}

std::string GetIsolatedFileSystemName(const GURL& origin_url,
                                      const std::string& filesystem_id) {
  std::string name(
      storage::GetFileSystemName(origin_url, storage::kFileSystemTypeIsolated));
  name.append("_");
  name.append(filesystem_id);
  return name;
}

bool CrackIsolatedFileSystemName(const std::string& filesystem_name,
                                 std::string* filesystem_id) {
  DCHECK(filesystem_id);

  // |filesystem_name| is of the form {origin}:isolated_{filesystem_id}.
  std::string start_token(":");
  start_token =
      start_token.append(GetFileSystemTypeString(kFileSystemTypeIsolated))
          .append("_");
  // WebKit uses different case in its constant for isolated file system
  // names, so we do a case insensitive compare by converting both strings
  // to uppercase.
  // TODO(benwells): Remove this when WebKit uses the same constant.
  start_token = base::ToUpperASCII(start_token);
  std::string filesystem_name_upper = base::ToUpperASCII(filesystem_name);
  size_t pos = filesystem_name_upper.find(start_token);
  if (pos == std::string::npos)
    return false;
  if (pos == 0)
    return false;

  *filesystem_id =
      filesystem_name.substr(pos + start_token.length(), std::string::npos);
  if (filesystem_id->empty())
    return false;

  return true;
}

bool ValidateIsolatedFileSystemId(const std::string& filesystem_id) {
  const size_t kExpectedFileSystemIdSize = 32;
  return (filesystem_id.size() == kExpectedFileSystemIdSize) &&
         base::ContainsOnlyChars(filesystem_id, "ABCDEF0123456789");
}

std::string GetIsolatedFileSystemRootURIString(
    const GURL& origin_url,
    const std::string& filesystem_id,
    const std::string& optional_root_name) {
  std::string root =
      GetFileSystemRootURI(origin_url, kFileSystemTypeIsolated).spec();
  if (base::FilePath::FromUTF8Unsafe(filesystem_id).ReferencesParent())
    return std::string();
  root.append(base::EscapePath(filesystem_id));
  root.append("/");
  if (!optional_root_name.empty()) {
    if (base::FilePath::FromUTF8Unsafe(optional_root_name).ReferencesParent())
      return std::string();
    root.append(base::EscapePath(optional_root_name));
    root.append("/");
  }
  return root;
}

std::string GetExternalFileSystemRootURIString(const GURL& origin_url,
                                               const std::string& mount_name) {
  std::string root =
      GetFileSystemRootURI(origin_url, kFileSystemTypeExternal).spec();
  if (base::FilePath::FromUTF8Unsafe(mount_name).ReferencesParent())
    return std::string();
  root.append(base::EscapePath(mount_name));
  root.append("/");
  return root;
}

base::File::Error NetErrorToFileError(int error) {
  switch (error) {
    case net::OK:
      return base::File::FILE_OK;
    case net::ERR_ADDRESS_IN_USE:
      return base::File::FILE_ERROR_IN_USE;
    case net::ERR_FILE_EXISTS:
      return base::File::FILE_ERROR_EXISTS;
    case net::ERR_FILE_NOT_FOUND:
      return base::File::FILE_ERROR_NOT_FOUND;
    case net::ERR_ACCESS_DENIED:
      return base::File::FILE_ERROR_ACCESS_DENIED;
    case net::ERR_INSUFFICIENT_RESOURCES:
      return base::File::FILE_ERROR_TOO_MANY_OPENED;
    case net::ERR_OUT_OF_MEMORY:
      return base::File::FILE_ERROR_NO_MEMORY;
    case net::ERR_FILE_NO_SPACE:
      return base::File::FILE_ERROR_NO_SPACE;
    case net::ERR_INVALID_ARGUMENT:
    case net::ERR_INVALID_HANDLE:
      return base::File::FILE_ERROR_INVALID_OPERATION;
    case net::ERR_ABORTED:
    case net::ERR_CONNECTION_ABORTED:
      return base::File::FILE_ERROR_ABORT;
    case net::ERR_ADDRESS_INVALID:
    case net::ERR_INVALID_URL:
      return base::File::FILE_ERROR_INVALID_URL;
    default:
      return base::File::FILE_ERROR_FAILED;
  }
}

}  // namespace storage