1 // Copyright (c) 2012 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. 4 5 #include "chromeos/cryptohome/system_salt_getter.h" 6 7 #include "base/bind.h" 8 #include "base/location.h" 9 #include "base/message_loop/message_loop_proxy.h" 10 #include "base/strings/string_number_conversions.h" 11 #include "base/strings/string_util.h" 12 #include "chromeos/dbus/cryptohome_client.h" 13 #include "chromeos/dbus/dbus_thread_manager.h" 14 15 namespace chromeos { 16 namespace { 17 18 SystemSaltGetter* g_system_salt_getter = NULL; 19 20 } // namespace 21 22 SystemSaltGetter::SystemSaltGetter() : weak_ptr_factory_(this) { 23 } 24 25 SystemSaltGetter::~SystemSaltGetter() { 26 } 27 28 void SystemSaltGetter::GetSystemSalt( 29 const GetSystemSaltCallback& callback) { 30 if (!system_salt_.empty()) { 31 base::MessageLoopProxy::current()->PostTask( 32 FROM_HERE, base::Bind(callback, system_salt_)); 33 return; 34 } 35 36 DBusThreadManager::Get()->GetCryptohomeClient()->WaitForServiceToBeAvailable( 37 base::Bind(&SystemSaltGetter::DidWaitForServiceToBeAvailable, 38 weak_ptr_factory_.GetWeakPtr(), 39 callback)); 40 } 41 42 void SystemSaltGetter::DidWaitForServiceToBeAvailable( 43 const GetSystemSaltCallback& callback, 44 bool service_is_available) { 45 if (!service_is_available) { 46 LOG(ERROR) << "WaitForServiceToBeAvailable failed."; 47 callback.Run(std::string()); 48 return; 49 } 50 DBusThreadManager::Get()->GetCryptohomeClient()->GetSystemSalt( 51 base::Bind(&SystemSaltGetter::DidGetSystemSalt, 52 weak_ptr_factory_.GetWeakPtr(), 53 callback)); 54 } 55 56 void SystemSaltGetter::DidGetSystemSalt(const GetSystemSaltCallback& callback, 57 DBusMethodCallStatus call_status, 58 const std::vector<uint8>& system_salt) { 59 if (call_status == DBUS_METHOD_CALL_SUCCESS && 60 !system_salt.empty() && 61 system_salt.size() % 2 == 0U) 62 system_salt_ = ConvertRawSaltToHexString(system_salt); 63 else 64 LOG(WARNING) << "System salt not available"; 65 66 callback.Run(system_salt_); 67 } 68 69 // static 70 void SystemSaltGetter::Initialize() { 71 CHECK(!g_system_salt_getter); 72 g_system_salt_getter = new SystemSaltGetter(); 73 } 74 75 // static 76 bool SystemSaltGetter::IsInitialized() { 77 return g_system_salt_getter; 78 } 79 80 // static 81 void SystemSaltGetter::Shutdown() { 82 CHECK(g_system_salt_getter); 83 delete g_system_salt_getter; 84 g_system_salt_getter = NULL; 85 } 86 87 // static 88 SystemSaltGetter* SystemSaltGetter::Get() { 89 CHECK(g_system_salt_getter) 90 << "SystemSaltGetter::Get() called before Initialize()"; 91 return g_system_salt_getter; 92 } 93 94 // static 95 std::string SystemSaltGetter::ConvertRawSaltToHexString( 96 const std::vector<uint8>& salt) { 97 return StringToLowerASCII(base::HexEncode( 98 reinterpret_cast<const void*>(salt.data()), salt.size())); 99 } 100 101 } // namespace chromeos 102