TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / common / loop_device.cpp
1 /*
2  * Copyright (C) 2017 Simon Fels <morphis@gravedo.de>
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 3, as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranties of
10  * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11  * PURPOSE.  See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  */
17
18 #include "anbox/common/loop_device.h"
19 #include "anbox/defer_action.h"
20
21 #include <system_error>
22
23 #include <linux/loop.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <sys/ioctl.h>
27
28 namespace anbox {
29 namespace common {
30 std::shared_ptr<LoopDevice> LoopDevice::create(const boost::filesystem::path &path) {
31   const auto fd = ::open(path.c_str(), O_RDWR);
32   if (fd < 0)
33     throw std::system_error{errno, std::system_category()};
34
35   return std::shared_ptr<LoopDevice>(new LoopDevice(Fd{fd}, path));
36 }
37
38 LoopDevice::LoopDevice(Fd fd, const boost::filesystem::path &path) :
39   fd_{fd}, path_{path} {}
40
41 LoopDevice::~LoopDevice() {
42   if (fd_ < 0)
43     return;
44
45   ::ioctl(fd_, LOOP_CLR_FD);
46   ::close(fd_);
47 }
48
49 bool LoopDevice::attach_file(const boost::filesystem::path &file_path) {
50   if (fd_ < 0)
51     return false;
52
53   int file_fd = ::open(file_path.c_str(), O_RDONLY);
54   if (file_fd < 0)
55     return false;
56
57   DeferAction close_file_fd{[&]() { ::close(file_fd); }};
58
59   if (::ioctl(fd_, LOOP_SET_FD, file_fd) < 0)
60     return false;
61
62   return true;
63 }
64 } // namespace common
65 } // namespace anbox