blob: e4b9e33af9e9710d5fea77ec0d0df90384b0a245 [file] [log] [blame]
Shawn Willden23d4a742015-03-19 15:33:21 -06001/*
2 * Copyright (C) 2015 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 "operation_table.h"
18
19#include <openssl/rand.h>
20
21#include "openssl_err.h"
22#include "operation.h"
23
24namespace keymaster {
25
26OperationTable::Entry::~Entry() {
27 delete operation;
28 operation = NULL;
29 handle = 0;
30}
31
32keymaster_error_t OperationTable::Add(Operation* operation,
33 keymaster_operation_handle_t* op_handle) {
34 if (!table_.get()) {
35 table_.reset(new Entry[table_size_]);
36 if (!table_.get())
37 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
38 }
39
40 UniquePtr<Operation> op(operation);
Shawn Willden34454982015-04-29 23:22:37 -060041 if (RAND_bytes(reinterpret_cast<uint8_t*>(op_handle), sizeof(*op_handle)) != 1)
Shawn Willden23d4a742015-03-19 15:33:21 -060042 return TranslateLastOpenSslError();
43 if (*op_handle == 0) {
44 // Statistically this is vanishingly unlikely, which means if it ever happens in practice,
45 // it indicates a broken RNG.
46 return KM_ERROR_UNKNOWN_ERROR;
47 }
48
49 for (size_t i = 0; i < table_size_; ++i) {
50 if (table_[i].operation == NULL) {
51 table_[i].operation = op.release();
52 table_[i].handle = *op_handle;
53 return KM_ERROR_OK;
54 }
55 }
56 return KM_ERROR_TOO_MANY_OPERATIONS;
57}
58
59Operation* OperationTable::Find(keymaster_operation_handle_t op_handle) {
60 if (op_handle == 0)
61 return NULL;
62
63 if (!table_.get())
64 return NULL;
65
66 for (size_t i = 0; i < table_size_; ++i) {
67 if (table_[i].handle == op_handle)
68 return table_[i].operation;
69 }
70 return NULL;
71}
72
73bool OperationTable::Delete(keymaster_operation_handle_t op_handle) {
74 if (!table_.get())
75 return false;
76
77 for (size_t i = 0; i < table_size_; ++i) {
78 if (table_[i].handle == op_handle) {
Chad Brubaker6f49e5f2015-03-20 13:54:21 -070079 delete table_[i].operation;
80 table_[i].operation = NULL;
81 table_[i].handle = 0;
Shawn Willden23d4a742015-03-19 15:33:21 -060082 return true;
83 }
84 }
85 return false;
86}
87
88} // namespace keymaster