Add checking return value
[platform/core/security/ode.git] / server / file-footer.cpp
1 /*
2  *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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 #include <fcntl.h>
17
18 #include <sstream>
19 #include <iomanip>
20
21 #include <klay/exception.h>
22 #include <klay/filesystem.h>
23
24 #include "logger.h"
25 #include "file-footer.h"
26 #include "key-manager/key-generator.h"
27
28 namespace ode {
29
30 namespace {
31
32 const std::string getFileName(const std::string &key)
33 {
34         BinaryData hash = KeyGenerator::SHA256(BinaryData(key.begin(), key.end()));
35         std::stringstream fileName;
36
37         fileName << "/opt/etc/.ode_";
38         fileName << std::hex << std::setfill('0') << std::setw(2);
39         for (unsigned int byte : hash) {
40                 fileName << byte;
41         }
42
43         return fileName.str();
44 }
45
46 } // namsepace
47
48 bool FileFooter::exist(const std::string &key)
49 {
50         std::string fileName(getFileName(key));
51
52         INFO(SINK, "Footer file : " + fileName);
53
54         runtime::File file(fileName);
55
56         return file.exists();
57 }
58
59 const BinaryData FileFooter::read(const std::string &key)
60 {
61         std::string fileName(getFileName(key));
62
63         INFO(SINK, "Footer file : " + fileName);
64
65         runtime::File file(fileName);
66         BinaryData value(file.size());
67
68         file.open(O_RDONLY);
69         file.read(value.data(), value.size());
70
71         return value;
72 }
73
74 void FileFooter::write(const std::string &key, const BinaryData &value)
75 {
76         std::string fileName(getFileName(key));
77
78         INFO(SINK, "Footer file : " + fileName);
79
80         runtime::File file(fileName);
81
82         if (!file.exists()) {
83                 file.create(S_IRUSR | S_IWUSR);
84         } else {
85                 file.open(O_RDWR);
86         }
87
88         file.write(value.data(), value.size());
89 }
90
91 void FileFooter::clear(const std::string &key)
92 {
93         std::string fileName(getFileName(key));
94
95         INFO(SINK, "Footer file : " + fileName);
96
97         runtime::File file(fileName);
98
99         file.remove();
100 }
101
102 } // namespace ode