1 // Copyright (c) 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 "xwalk/application/common/id_util.h"
7 #include "base/files/file_path.h"
8 #include "base/strings/string_util.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "crypto/sha2.h"
11 #include "xwalk/application/common/application_manifest_constants.h"
12 #include "xwalk/application/common/manifest_handlers/tizen_application_handler.h"
15 #include "third_party/re2/re2/re2.h"
19 namespace application {
22 const char kWGTAppIdPattern[] = "\\A([0-9a-zA-Z]{10})[.][0-9a-zA-Z]{1,52}\\z";
23 const char kXPKAppIdPattern[] = "\\Axwalk[.]([a-p]{32})\\z";
24 const std::string kAppIdPrefix("xwalk.");
26 const size_t kIdSize = 16;
29 // Converts a normal hexadecimal string into the alphabet used by applications.
30 // We use the characters 'a'-'p' instead of '0'-'f' to avoid ever having a
31 // completely numeric host, since some software interprets that as an IP
33 static void ConvertHexadecimalToIDAlphabet(std::string* id) {
34 for (size_t i = 0; i < id->size(); ++i) {
36 if (base::HexStringToInt(base::StringPiece(
37 id->begin() + i, id->begin() + i + 1), &val)) {
45 std::string GenerateId(const std::string& input) {
47 crypto::SHA256HashString(input, hash, sizeof(hash));
48 std::string output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
49 ConvertHexadecimalToIDAlphabet(&output);
52 return kAppIdPrefix + output;
58 std::string GenerateIdForPath(const base::FilePath& path) {
59 std::string path_bytes =
60 std::string(reinterpret_cast<const char*>(path.value().data()),
61 path.value().size() * sizeof(base::FilePath::CharType));
62 return GenerateId(path_bytes);
65 bool IsValidApplicationID(const std::string& id) {
67 if (RE2::FullMatch(id, kWGTAppIdPattern) ||
68 RE2::FullMatch(id, kXPKAppIdPattern))
73 std::string temp = StringToLowerASCII(id);
74 // Verify that the id is legal.
75 if (temp.size() != (kIdSize * 2))
78 // We only support lowercase IDs, because IDs can be used as URL components
79 // (where GURL will lowercase it).
80 for (size_t i = 0; i < temp.size(); ++i)
81 if (temp[i] < 'a' || temp[i] > 'p')
88 std::string GetPackageIdFromAppId(const std::string& app_id) {
89 std::string package_id;
90 if (RE2::FullMatch(app_id, kWGTAppIdPattern, &package_id) ||
91 RE2::FullMatch(app_id, kXPKAppIdPattern, &package_id)) {
94 LOG(ERROR) << "Cannot get package_id from invalid app id";
100 } // namespace application