1 // 2 // Copyright (C) 2014 The Android Open Source Project 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 #include "trunks/scoped_key_handle.h" 18 19 #include <base/logging.h> 20 21 #include "trunks/error_codes.h" 22 23 namespace { 24 25 const trunks::TPM_HANDLE kInvalidHandle = 0; 26 27 } // namespace 28 29 namespace trunks { 30 ScopedKeyHandle(const TrunksFactory & factory)31ScopedKeyHandle::ScopedKeyHandle(const TrunksFactory& factory) 32 : factory_(factory), 33 handle_(kInvalidHandle) {} 34 ScopedKeyHandle(const TrunksFactory & factory,TPM_HANDLE handle)35ScopedKeyHandle::ScopedKeyHandle(const TrunksFactory& factory, 36 TPM_HANDLE handle) 37 : factory_(factory), 38 handle_(handle) {} 39 ~ScopedKeyHandle()40ScopedKeyHandle::~ScopedKeyHandle() { 41 if (handle_ != kInvalidHandle) { 42 FlushHandleContext(handle_); 43 } 44 } 45 release()46TPM_HANDLE ScopedKeyHandle::release() { 47 TPM_HANDLE tmp_handle = handle_; 48 handle_ = kInvalidHandle; 49 return tmp_handle; 50 } 51 reset(TPM_HANDLE new_handle)52void ScopedKeyHandle::reset(TPM_HANDLE new_handle) { 53 TPM_HANDLE tmp_handle = handle_; 54 handle_ = new_handle; 55 if (tmp_handle != kInvalidHandle) { 56 FlushHandleContext(tmp_handle); 57 } 58 } 59 reset()60void ScopedKeyHandle::reset() { 61 reset(kInvalidHandle); 62 } 63 ptr()64TPM_HANDLE* ScopedKeyHandle::ptr() { 65 return &handle_; 66 } 67 get() const68TPM_HANDLE ScopedKeyHandle::get() const { 69 return handle_; 70 } 71 FlushHandleContext(TPM_HANDLE handle)72void ScopedKeyHandle::FlushHandleContext(TPM_HANDLE handle) { 73 TPM_RC result = TPM_RC_SUCCESS; 74 result = factory_.GetTpm()->FlushContextSync(handle, nullptr); 75 if (result) { 76 LOG(WARNING) << "Error closing handle: " << handle << " : " 77 << GetErrorString(result); 78 } 79 } 80 81 } // namespace trunks 82