ec1ab6d015d39ae8450543307a91d2a18cc324f9
[platform/core/security/trust-anchor.git] / src / file-system.cpp
1 /*
2  *  Copyright (c) 2017 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 /*
17  * @file        file-system.cpp
18  * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
19  * @version     1.0
20  * @brief
21  */
22 #include "file-system.hxx"
23
24 #include <climits>
25 #include <cerrno>
26 #include <unistd.h>
27 #include <cstdio>
28
29 #include <vector>
30
31 #include "exception.hxx"
32
33 namespace tanchor {
34
35 void File::linkTo(const std::string &src, const std::string &dst)
36 {
37         if (::symlink(src.c_str(), dst.c_str()))
38                 ThrowErrno(errno, "Failed to link " + src + " -> " + dst);
39 }
40
41 std::string File::read(const std::string &path)
42 {
43         FilePtr fp = FilePtr(::fopen(path.c_str(), "rb"), ::fclose);
44         if (fp == nullptr)
45                 throw std::invalid_argument("Failed to open [" + path + "].");
46
47         std::fseek(fp.get(), 0L, SEEK_END);
48         unsigned int fsize = std::ftell(fp.get());
49         std::rewind(fp.get());
50
51         std::string buff(fsize, 0);
52         if (fsize != std::fread(static_cast<void*>(&buff[0]), 1, fsize, fp.get()))
53                 throw std::logic_error("Failed to read [" + path + "]");
54         return buff;
55 }
56
57 std::string File::readLink(const std::string &path)
58 {
59         std::vector<char> buf(PATH_MAX);
60         ssize_t count = ::readlink(path.c_str(), buf.data(), buf.size());
61         return std::string(buf.data(), (count > 0) ? count : 0);
62 }
63
64 std::string File::getName(const std::string &path)
65 {
66         size_t pos = path.rfind('/');
67         if (pos == std::string::npos)
68                 throw std::invalid_argument("Path is wrong. > " + path);
69         return path.substr(pos + 1);
70 }
71
72 } // namespace tanchor