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#ifndef TRUNKS_SCOPED_KEY_HANDLE_H_
18#define TRUNKS_SCOPED_KEY_HANDLE_H_
19
20#include "trunks/tpm_generated.h"
21#include "trunks/trunks_export.h"
22#include "trunks/trunks_factory.h"
23
24namespace trunks {
25
26// This class is used to wrap a Key or NV ram handle given by the TPM.
27// It provides a destructor that cleans up TPM resources associated with
28// that handle.
29class TRUNKS_EXPORT ScopedKeyHandle {
30 public:
31  // We provide a factory to the constructor so that we can later free
32  // resources associated with the handle.
33  explicit ScopedKeyHandle(const TrunksFactory& factory);
34  ScopedKeyHandle(const TrunksFactory& factory, TPM_HANDLE handle);
35  virtual ~ScopedKeyHandle();
36
37  // This method releases the TPM_HANDLE associated with this class.
38  // It returns the handle that was previously wrapped, and returns
39  // INVALID_HANDLE if the previous handle was unset.
40  virtual TPM_HANDLE release();
41
42  // This method flushes all context associated with the current handle,
43  // and has the class wrap |new_handle|
44  virtual void reset(TPM_HANDLE new_handle);
45
46  // This method flushes all context associated with the current handle,
47  // and resets the internal handle of the class to the uninitialized value.
48  // Note: After reset() this class should not be used again till a new handle
49  // is injected.
50  virtual void reset();
51
52  // This method returns a pointer to the handle associated with this class.
53  // This method does not transfer ownership.
54  virtual TPM_HANDLE* ptr();
55
56  // This method returns the handle currectly associated with the class.
57  // This method does not transfer ownership, therefore the handle returned
58  // might be stale.
59  virtual TPM_HANDLE get() const;
60
61 private:
62  const TrunksFactory& factory_;
63  TPM_HANDLE handle_;
64  void FlushHandleContext(TPM_HANDLE handle);
65
66  DISALLOW_COPY_AND_ASSIGN(ScopedKeyHandle);
67};
68
69}  // namespace trunks
70
71#endif  // TRUNKS_SCOPED_KEY_HANDLE_H_
72