1 // Copyright 2013 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 "extensions/common/file_util.h"
9 #include "base/file_util.h"
10 #include "base/files/file_path.h"
11 #include "net/base/escape.h"
14 namespace extensions
{
17 base::FilePath
ExtensionURLToRelativeFilePath(const GURL
& url
) {
18 std::string url_path
= url
.path();
19 if (url_path
.empty() || url_path
[0] != '/')
20 return base::FilePath();
22 // Drop the leading slashes and convert %-encoded UTF8 to regular UTF8.
23 std::string file_path
= net::UnescapeURLComponent(url_path
,
24 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
);
25 size_t skip
= file_path
.find_first_not_of("/\\");
26 if (skip
!= file_path
.npos
)
27 file_path
= file_path
.substr(skip
);
29 base::FilePath path
= base::FilePath::FromUTF8Unsafe(file_path
);
31 // It's still possible for someone to construct an annoying URL whose path
32 // would still wind up not being considered relative at this point.
33 // For example: chrome-extension://id/c:////foo.html
34 if (path
.IsAbsolute())
35 return base::FilePath();
40 base::FilePath
ExtensionResourceURLToFilePath(const GURL
& url
,
41 const base::FilePath
& root
) {
42 std::string host
= net::UnescapeURLComponent(url
.host(),
43 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
);
45 return base::FilePath();
47 base::FilePath relative_path
= ExtensionURLToRelativeFilePath(url
);
48 if (relative_path
.empty())
49 return base::FilePath();
51 base::FilePath path
= root
.AppendASCII(host
).Append(relative_path
);
52 if (!base::PathExists(path
))
53 return base::FilePath();
54 path
= base::MakeAbsoluteFilePath(path
);
55 if (path
.empty() || !root
.IsParent(path
))
56 return base::FilePath();
60 } // namespace file_util
61 } // namespace extensions