2 * Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
4 * Contact: Bumjin Im <bj.im@samsung.com>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License
19 * @file password-file-buffer.h
20 * @author Lukasz Kostyra (l.kostyra@partner.samsung.com)
22 * @brief Implementation of PasswordFileBuffer, used for serialization in PasswordFile class
25 #include <password-file-buffer.h>
30 #include <dpl/log/log.h>
32 #include <security-server.h>
33 #include <password-exception.h>
37 namespace SecurityServer
39 PasswordFileBuffer::PasswordFileBuffer(): m_bufferReadBytes(0) {}
41 void PasswordFileBuffer::Read(size_t num, void *bytes)
43 if(m_buffer.empty()) {
44 LogError("Buffer doesn't contain any data.");
45 Throw(PasswordException::NoData);
48 if((m_bufferReadBytes + num) > m_buffer.size()) {
49 LogError("Not enough buffer to read " << num << " data.");
50 Throw(PasswordException::OutOfData);
53 void* ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
56 LogError("Failed to read " << num << " bytes.");
57 Throw(PasswordException::MemoryError);
60 m_bufferReadBytes += num;
63 void PasswordFileBuffer::Write(size_t num, const void *bytes)
65 const char* buffer = static_cast<const char*>(bytes);
66 std::copy(buffer, buffer+num, std::back_inserter(m_buffer));
69 void PasswordFileBuffer::Save(const std::string &path)
71 std::ofstream file(path, std::ofstream::trunc);
74 LogError("Error while opening file stream.");
75 Throw(PasswordException::FStreamOpenError);
78 file.write(m_buffer.data(), m_buffer.size());
80 LogError("Failed to write data.");
81 Throw(PasswordException::FStreamWriteError);
84 int fd = open(path.c_str(), O_WRONLY | O_APPEND); fsync(fd); close(fd);
87 void PasswordFileBuffer::Load(const std::string &path)
89 std::ifstream file(path, std::ifstream::binary);
92 LogError("Error while opening file stream.");
93 Throw(PasswordException::FStreamOpenError);
96 //reset read bytes counter
97 m_bufferReadBytes = 0;
99 m_buffer.assign(std::istreambuf_iterator<char>(file),
100 std::istreambuf_iterator<char>());
103 LogError("Failed to read data. Failbit: " << file.fail() << ", Badbit: " << file.bad());
104 Throw(PasswordException::FStreamReadError);
108 } //namespace SecurityServer