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), handle_(kInvalidHandle) {} 33 ScopedKeyHandle(const TrunksFactory & factory,TPM_HANDLE handle)34ScopedKeyHandle::ScopedKeyHandle(const TrunksFactory& factory, 35 TPM_HANDLE handle) 36 : factory_(factory), handle_(handle) {} 37 ~ScopedKeyHandle()38ScopedKeyHandle::~ScopedKeyHandle() { 39 if (handle_ != kInvalidHandle) { 40 FlushHandleContext(handle_); 41 } 42 } 43 release()44TPM_HANDLE ScopedKeyHandle::release() { 45 TPM_HANDLE tmp_handle = handle_; 46 handle_ = kInvalidHandle; 47 return tmp_handle; 48 } 49 reset(TPM_HANDLE new_handle)50void ScopedKeyHandle::reset(TPM_HANDLE new_handle) { 51 TPM_HANDLE tmp_handle = handle_; 52 handle_ = new_handle; 53 if (tmp_handle != kInvalidHandle) { 54 FlushHandleContext(tmp_handle); 55 } 56 } 57 reset()58void ScopedKeyHandle::reset() { 59 reset(kInvalidHandle); 60 } 61 ptr()62TPM_HANDLE* ScopedKeyHandle::ptr() { 63 return &handle_; 64 } 65 get() const66TPM_HANDLE ScopedKeyHandle::get() const { 67 return handle_; 68 } 69 FlushHandleContext(TPM_HANDLE handle)70void ScopedKeyHandle::FlushHandleContext(TPM_HANDLE handle) { 71 TPM_RC result = TPM_RC_SUCCESS; 72 result = factory_.GetTpm()->FlushContextSync(handle, nullptr); 73 if (result) { 74 LOG(WARNING) << "Error closing handle: " << handle << " : " 75 << GetErrorString(result); 76 } 77 } 78 79 } // namespace trunks 80