summaryrefslogtreecommitdiff
path: root/src/manager/service/file-system.cpp
blob: e569d1ddde4d29ef0892aeb427842e190f9c01f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
 *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 *
 * @file        FileSystem.cpp
 * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
 * @version     1.0
 * @brief       Sample service implementation.
 */
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>

#include <cstdlib>
#include <string>
#include <sstream>
#include <fstream>
#include <memory>
#include <stdexcept>

#include <dpl/errno_string.h>
#include <dpl/fstream_accessors.h>
#include <dpl/log/log.h>

#include <exception.h>
#include <file-system.h>

namespace {

const std::string CKM_DATA_PATH = "/opt/data/ckm/";
const std::string CKM_KEY_PREFIX = "key-";
const std::string CKM_DB_KEY_PREFIX = "db-key-";
const std::string CKM_DB_PREFIX = "db-";
const std::string CKM_REMOVED_APP_PREFIX = "removed-app-";
const std::string CKM_LOCK_FILE = "/var/run/key-manager.pid";

} // namespace anonymous

namespace CKM {

FileSystem::FileSystem(uid_t uid)
  : m_uid(uid)
{
}

std::string FileSystem::getDBPath() const
{
    std::stringstream ss;
    ss << CKM_DATA_PATH << CKM_DB_PREFIX << m_uid;
    return ss.str();
}

std::string FileSystem::getDKEKPath() const
{
    std::stringstream ss;
    ss << CKM_DATA_PATH << CKM_KEY_PREFIX << m_uid;
    return ss.str();
}

std::string FileSystem::getDBDEKPath() const
{
    std::stringstream ss;
    ss << CKM_DATA_PATH << CKM_DB_KEY_PREFIX << m_uid;
    return ss.str();
}

std::string FileSystem::getRemovedAppsPath() const
{
    std::stringstream ss;
    ss << CKM_DATA_PATH << CKM_REMOVED_APP_PREFIX << m_uid;
    return ss.str();
}

RawBuffer FileSystem::loadFile(const std::string &path) const
{
    std::ifstream is(path);

    if (is.fail() && ENOENT == errno)
        return RawBuffer();

    if (is.fail()) {
        auto description = GetErrnoString(errno);
        ThrowErr(Exc::FileSystemFailed,
                 "Error opening file: ", path, " Reason: ", description);
    }

    std::istreambuf_iterator<char> begin(is), end;
    std::vector<char> buff(begin, end); // This trick does not work with boost vector

    RawBuffer buffer(buff.size());
    memcpy(buffer.data(), buff.data(), buff.size());
    return buffer;
}

RawBuffer FileSystem::getDKEK() const
{
    return loadFile(getDKEKPath());
}

RawBuffer FileSystem::getDBDEK() const
{
    return loadFile(getDBDEKPath());
}

void FileSystem::saveFile(const std::string &path, const RawBuffer &buffer) const
{
    std::ofstream os(path, std::ios::out | std::ofstream::binary | std::ofstream::trunc);
    std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator<char>(os));

    // Prevent desynchronization in batter remove test.
    os.flush();
    fsync(FstreamAccessors<std::ofstream>::GetFd(os)); // flush kernel space buffer
    os.close();

    if (os.fail())
        ThrowErr(Exc::FileSystemFailed, "Failed to save file: ", path);
}

void FileSystem::saveDKEK(const RawBuffer &buffer) const
{
    saveFile(getDKEKPath(), buffer);
}

void FileSystem::saveDBDEK(const RawBuffer &buffer) const
{
    saveFile(getDBDEKPath(), buffer);
}

void FileSystem::addRemovedApp(const std::string &smackLabel) const
{
    std::ofstream outfile;
    outfile.open(getRemovedAppsPath(), std::ios_base::app);
    outfile << smackLabel << std::endl;
    outfile.close();
    if (outfile.fail()) {
        auto desc = GetErrnoString(errno);
        ThrowErr(Exc::FileSystemFailed,
                 "Could not update file: ", getRemovedAppsPath(), " Reason: ", desc);
    }
}

AppLabelVector FileSystem::clearRemovedsApps() const
{
    // read the contents
    AppLabelVector removedApps;
    std::string line;
    std::ifstream removedAppsFile(getRemovedAppsPath());
    if (removedAppsFile.is_open()) {
        while (!removedAppsFile.eof()) {
            getline(removedAppsFile, line);
            if (line.size() > 0)
                removedApps.push_back(line);
        }
        removedAppsFile.close();
    }
    // truncate the contents
    std::ofstream truncateFile;
    truncateFile.open(getRemovedAppsPath(), std::ofstream::out | std::ofstream::trunc);
    truncateFile.close();
    return removedApps;
}

int FileSystem::init()
{
    errno = 0;
    if ((mkdir(CKM_DATA_PATH.c_str(), 0700)) && (errno != EEXIST)) {
        int err = errno;
        LogError("Error in mkdir " << CKM_DATA_PATH << ". Reason: " << GetErrnoString(err));
        return -1; // TODO set up some error code
    }
    return 0;
}

UidVector FileSystem::getUIDsFromDBFile()
{
    UidVector uids;
    std::unique_ptr<DIR, std::function<int(DIR*)>>
        dirp(::opendir(CKM_DATA_PATH.c_str()), ::closedir);

    if (!dirp.get()) {
        int err = errno;
        LogError("Error in opendir. Data directory could not be read. Error: " << GetErrnoString(err));
        return UidVector();
    }

    size_t len = offsetof(struct dirent, d_name) + pathconf(CKM_DATA_PATH.c_str(), _PC_NAME_MAX) + 1;
    std::unique_ptr<struct dirent, std::function<void(void*)>>
        pEntry(static_cast<struct dirent*>(::malloc(len)), ::free);

    if (!pEntry.get()) {
        LogError("Memory allocation failed.");
        return UidVector();
    }

    struct dirent* pDirEntry = NULL;

    while ( (!readdir_r(dirp.get(), pEntry.get(), &pDirEntry)) && pDirEntry ) {
        // Ignore files with diffrent prefix
        if (strncmp(pDirEntry->d_name, CKM_KEY_PREFIX.c_str(), CKM_KEY_PREFIX.size()))
            continue;

        // We find database. Let's extract user id.
        try {
            uids.push_back(static_cast<uid_t>(std::stoi((pDirEntry->d_name)+CKM_KEY_PREFIX.size())));
        } catch (const std::invalid_argument) {
            LogDebug("Error in extracting uid from db file. Error=std::invalid_argument."
                "This will be ignored.File=" << pDirEntry->d_name << "");
        } catch(const std::out_of_range) {
            LogDebug("Error in extracting uid from db file. Error=std::out_of_range."
                "This will be ignored. File="<< pDirEntry->d_name << "");
        }
    }

    return uids;
}

int FileSystem::removeUserData() const
{
    int err, retCode = 0;

    if (unlink(getDBPath().c_str())) {
        retCode = -1;
        err = errno;
        LogDebug("Error in unlink user database: " << getDBPath()
            << "Errno: " << errno << " " << GetErrnoString(err));
    }

    if (unlink(getDKEKPath().c_str())) {
        retCode = -1;
        err = errno;
        LogDebug("Error in unlink user DKEK: " << getDKEKPath()
            << "Errno: " << errno << " " << GetErrnoString(err));
    }

    if (unlink(getDBDEKPath().c_str())) {
        retCode = -1;
        err = errno;
        LogDebug("Error in unlink user DBDEK: " << getDBDEKPath()
            << "Errno: " << errno << " " << GetErrnoString(err));
    }

    if (unlink(getRemovedAppsPath().c_str())) {
        retCode = -1;
        err = errno;
        LogDebug("Error in unlink user's Removed Apps File: " << getRemovedAppsPath()
            << "Errno: " << errno << " " << GetErrnoString(err));
    }

    return retCode;
}

FileLock FileSystem::lock()
{
    FileLock fl(CKM_LOCK_FILE.c_str());
    return fl;
}

} // namespace CKM