1 /*
2  * Copyright 2016 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 "secure_storage.h"
18 
19 namespace avb {
20 
~SecureStorage()21 SecureStorage::~SecureStorage() {
22     close();
23 }
24 
open(const char * name)25 int SecureStorage::open(const char* name) {
26     // Close any storage session/file still open
27     close();
28     error_ = storage_open_session(&session_handle_, STORAGE_CLIENT_TP_PORT);
29     if (error_ < 0) {
30         return error_;
31     }
32     error_ = storage_open_file(session_handle_, &file_handle_, name,
33                                STORAGE_FILE_OPEN_CREATE, 0 /* don't commit */);
34     return error_;
35 }
36 
delete_file(const char * name)37 int SecureStorage::delete_file(const char* name) {
38     // Reuse existing storage session if possible
39     if (session_handle_ == 0) {
40         error_ = storage_open_session(&session_handle_, STORAGE_CLIENT_TP_PORT);
41     }
42     if (error_ < 0) {
43         return error_;
44     }
45     return storage_delete_file(session_handle_, name, STORAGE_OP_COMPLETE);
46 }
47 
read(uint64_t off,void * buf,size_t size) const48 int SecureStorage::read(uint64_t off, void* buf, size_t size) const {
49     if (error_ < 0) {
50         return error_;
51     }
52     return storage_read(file_handle_, off, buf, size);
53 }
54 
get_file_size(uint64_t * size) const55 int SecureStorage::get_file_size(uint64_t* size) const {
56     if (error_ < 0) {
57         return error_;
58     }
59     return storage_get_file_size(file_handle_, size);
60 }
61 
write(uint64_t off,const void * buf,size_t size) const62 int SecureStorage::write(uint64_t off, const void* buf, size_t size) const {
63     if (error_ < 0) {
64         return error_;
65     }
66     return storage_write(file_handle_, off, buf, size, STORAGE_OP_COMPLETE);
67 }
68 
close()69 void SecureStorage::close() {
70     if (error_ < 0) {
71         return;
72     }
73     if (file_handle_) {
74         storage_close_file(file_handle_);
75     }
76     if (session_handle_) {
77         storage_close_session(session_handle_);
78     }
79     file_handle_ = 0;
80     session_handle_ = 0;
81     error_ = -EINVAL;
82 }
83 
84 }  // namespace avb
85