Roll src/third_party/WebKit 9f7fb92:f103b33 (svn 202621:202622)
[chromium-blink-merge.git] / components / resource_provider / file_utils.cc
blob5b8eac5f6f4fc8ca86f1a72909c99d6fa0d363a0
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/resource_provider/file_utils.h"
7 #include "base/files/file_path.h"
8 #include "base/path_service.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "url/gurl.h"
13 namespace resource_provider {
14 namespace {
16 bool IsPathNameValid(const std::string& name) {
17 if (name.empty() || name == "." || name == "..")
18 return false;
20 for (auto c : name) {
21 if (!base::IsAsciiAlpha(c) && !base::IsAsciiDigit(c) &&
22 c != '_' && c != '.')
23 return false;
25 return true;
28 } // namespace
30 base::FilePath GetPathForApplicationUrl(const GURL& application_url) {
31 if (application_url.scheme() != "mojo")
32 return base::FilePath();
34 std::string path = application_url.path();
35 base::TrimString(path, "/", &path);
37 if (!IsPathNameValid(path))
38 return base::FilePath();
40 base::FilePath base_path;
41 #if defined(OS_ANDROID)
42 PathService::Get(base::DIR_ANDROID_APP_DATA, &base_path);
43 // |base_path| on android has an additional path, need to go up a level to get
44 // at other apps resources.
45 base_path = base_path.DirName();
46 base_path = base_path.AppendASCII("app_cached_apps");
47 #else
48 PathService::Get(base::DIR_EXE, &base_path);
49 #endif
50 return base_path.AppendASCII(path).AppendASCII("resources");
53 base::FilePath GetPathForResourceNamed(const base::FilePath& app_path,
54 const std::string& resource_path) {
55 CHECK(!app_path.empty());
57 if (resource_path.empty() || resource_path[0] == '/' ||
58 resource_path[resource_path.size() - 1] == '/' ||
59 resource_path.find("//") != std::string::npos)
60 return base::FilePath();
62 std::vector<std::string> path_components = base::SplitString(
63 resource_path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
64 if (path_components.empty())
65 return base::FilePath();
67 base::FilePath result(app_path);
68 for (const auto& path_component : path_components) {
69 if (!IsPathNameValid(path_component))
70 return base::FilePath();
71 result = result.AppendASCII(path_component);
73 return result;
76 } // namespace resource_provider