1 /*
2 * Copyright (C) 2016 The Android Open Source Project
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 specic language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "libappfuse/FuseBuffer.h"
18
19 #include <inttypes.h>
20 #include <string.h>
21 #include <unistd.h>
22
23 #include <algorithm>
24 #include <type_traits>
25
26 #include <sys/socket.h>
27 #include <sys/uio.h>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/macros.h>
32
33 namespace android {
34 namespace fuse {
35 namespace {
36
37 constexpr useconds_t kRetrySleepForWriting = 1000; // 1 ms
38 // This makes the total wait time to allocate a buffer 5 seconds
39 const int kNumberOfRetriesForWriting = 5000;
40
41 template <typename T>
CheckHeaderLength(const FuseMessage<T> * self,const char * name,size_t max_size)42 bool CheckHeaderLength(const FuseMessage<T>* self, const char* name, size_t max_size) {
43 const auto& header = static_cast<const T*>(self)->header;
44 if (header.len >= sizeof(header) && header.len <= max_size) {
45 return true;
46 } else {
47 LOG(ERROR) << "Invalid header length is found in " << name << ": " << header.len;
48 return false;
49 }
50 }
51
52 template <typename T>
ReadInternal(FuseMessage<T> * self,int fd,int sockflag)53 ResultOrAgain ReadInternal(FuseMessage<T>* self, int fd, int sockflag) {
54 char* const buf = reinterpret_cast<char*>(self);
55 const ssize_t result = sockflag ? TEMP_FAILURE_RETRY(recv(fd, buf, sizeof(T), sockflag))
56 : TEMP_FAILURE_RETRY(read(fd, buf, sizeof(T)));
57
58 switch (result) {
59 case 0:
60 // Expected EOF.
61 return ResultOrAgain::kFailure;
62 case -1:
63 if (errno == EAGAIN) {
64 return ResultOrAgain::kAgain;
65 }
66 PLOG(ERROR) << "Failed to read a FUSE message";
67 return ResultOrAgain::kFailure;
68 }
69
70 const auto& header = static_cast<const T*>(self)->header;
71 if (result < static_cast<ssize_t>(sizeof(header))) {
72 LOG(ERROR) << "Read bytes " << result << " are shorter than header size " << sizeof(header);
73 return ResultOrAgain::kFailure;
74 }
75
76 if (!CheckHeaderLength<T>(self, "Read", sizeof(T))) {
77 return ResultOrAgain::kFailure;
78 }
79
80 if (static_cast<uint32_t>(result) != header.len) {
81 LOG(ERROR) << "Read bytes " << result << " are different from header.len " << header.len;
82 return ResultOrAgain::kFailure;
83 }
84
85 return ResultOrAgain::kSuccess;
86 }
87
88 template <typename T>
WriteInternal(const FuseMessage<T> * self,int fd,int sockflag,const void * data,size_t max_size)89 ResultOrAgain WriteInternal(const FuseMessage<T>* self, int fd, int sockflag, const void* data,
90 size_t max_size) {
91 if (!CheckHeaderLength<T>(self, "Write", max_size)) {
92 return ResultOrAgain::kFailure;
93 }
94
95 const char* const buf = reinterpret_cast<const char*>(self);
96 const auto& header = static_cast<const T*>(self)->header;
97 int retry = kNumberOfRetriesForWriting;
98
99 while (true) {
100 int result;
101 if (sockflag) {
102 CHECK(data == nullptr);
103 result = TEMP_FAILURE_RETRY(send(fd, buf, header.len, sockflag));
104 } else if (data) {
105 const struct iovec vec[] = {{const_cast<char*>(buf), sizeof(header)},
106 {const_cast<void*>(data), header.len - sizeof(header)}};
107 result = TEMP_FAILURE_RETRY(writev(fd, vec, arraysize(vec)));
108 } else {
109 result = TEMP_FAILURE_RETRY(write(fd, buf, header.len));
110 }
111 if (result == -1) {
112 switch (errno) {
113 case ENOBUFS:
114 // When returning ENOBUFS, epoll still reports the FD is writable. Just usleep
115 // and retry again.
116 if (retry > 0) {
117 usleep(kRetrySleepForWriting);
118 retry--;
119 continue;
120 } else {
121 LOG(ERROR) << "Failed to write a FUSE message: ENOBUFS retries are failed";
122 return ResultOrAgain::kFailure;
123 }
124 case EAGAIN:
125 return ResultOrAgain::kAgain;
126 default:
127 PLOG(ERROR) << "Failed to write a FUSE message: "
128 << "fd=" << fd << " "
129 << "sockflag=" << sockflag << " "
130 << "data=" << data;
131 return ResultOrAgain::kFailure;
132 }
133 }
134
135 if (static_cast<unsigned int>(result) != header.len) {
136 LOG(ERROR) << "Written bytes " << result << " is different from length in header "
137 << header.len;
138 return ResultOrAgain::kFailure;
139 }
140 return ResultOrAgain::kSuccess;
141 }
142 }
143 }
144
145 static_assert(std::is_standard_layout<FuseBuffer>::value,
146 "FuseBuffer must be standard layout union.");
147
SetupMessageSockets(base::unique_fd (* result)[2])148 bool SetupMessageSockets(base::unique_fd (*result)[2]) {
149 base::unique_fd fds[2];
150 {
151 int raw_fds[2];
152 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_fds) == -1) {
153 PLOG(ERROR) << "Failed to create sockets for proxy";
154 return false;
155 }
156 fds[0].reset(raw_fds[0]);
157 fds[1].reset(raw_fds[1]);
158 }
159
160 constexpr int kMaxMessageSize = sizeof(FuseBuffer);
161 if (setsockopt(fds[0], SOL_SOCKET, SO_SNDBUF, &kMaxMessageSize, sizeof(int)) != 0 ||
162 setsockopt(fds[1], SOL_SOCKET, SO_SNDBUF, &kMaxMessageSize, sizeof(int)) != 0) {
163 PLOG(ERROR) << "Failed to update buffer size for socket";
164 return false;
165 }
166
167 (*result)[0] = std::move(fds[0]);
168 (*result)[1] = std::move(fds[1]);
169 return true;
170 }
171
172 template <typename T>
Read(int fd)173 bool FuseMessage<T>::Read(int fd) {
174 return ReadInternal(this, fd, 0) == ResultOrAgain::kSuccess;
175 }
176
177 template <typename T>
ReadOrAgain(int fd)178 ResultOrAgain FuseMessage<T>::ReadOrAgain(int fd) {
179 return ReadInternal(this, fd, MSG_DONTWAIT);
180 }
181
182 template <typename T>
Write(int fd) const183 bool FuseMessage<T>::Write(int fd) const {
184 return WriteInternal(this, fd, 0, nullptr, sizeof(T)) == ResultOrAgain::kSuccess;
185 }
186
187 template <typename T>
WriteWithBody(int fd,size_t max_size,const void * data) const188 bool FuseMessage<T>::WriteWithBody(int fd, size_t max_size, const void* data) const {
189 CHECK(data != nullptr);
190 return WriteInternal(this, fd, 0, data, max_size) == ResultOrAgain::kSuccess;
191 }
192
193 template <typename T>
WriteOrAgain(int fd) const194 ResultOrAgain FuseMessage<T>::WriteOrAgain(int fd) const {
195 return WriteInternal(this, fd, MSG_DONTWAIT, nullptr, sizeof(T));
196 }
197
Reset(uint32_t data_length,uint32_t opcode,uint64_t unique)198 void FuseRequest::Reset(
199 uint32_t data_length, uint32_t opcode, uint64_t unique) {
200 memset(this, 0, sizeof(fuse_in_header) + data_length);
201 header.len = sizeof(fuse_in_header) + data_length;
202 header.opcode = opcode;
203 header.unique = unique;
204 }
205
206 template <size_t N>
ResetHeader(uint32_t data_length,int32_t error,uint64_t unique)207 void FuseResponseBase<N>::ResetHeader(uint32_t data_length, int32_t error, uint64_t unique) {
208 CHECK_LE(error, 0) << "error should be zero or negative.";
209 header.len = sizeof(fuse_out_header) + data_length;
210 header.error = error;
211 header.unique = unique;
212 }
213
214 template <size_t N>
Reset(uint32_t data_length,int32_t error,uint64_t unique)215 void FuseResponseBase<N>::Reset(uint32_t data_length, int32_t error, uint64_t unique) {
216 memset(this, 0, sizeof(fuse_out_header) + data_length);
217 ResetHeader(data_length, error, unique);
218 }
219
HandleInit()220 void FuseBuffer::HandleInit() {
221 const fuse_init_in* const in = &request.init_in;
222
223 // Before writing |out|, we need to copy data from |in|.
224 const uint64_t unique = request.header.unique;
225 const uint32_t minor = in->minor;
226 const uint32_t max_readahead = in->max_readahead;
227
228 // Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
229 // defined (fuse version 7.6). The structure is the same from 7.6 through
230 // 7.22. Beginning with 7.23, the structure increased in size and added
231 // new parameters.
232 if (in->major != FUSE_KERNEL_VERSION || in->minor < 6) {
233 LOG(ERROR) << "Fuse kernel version mismatch: Kernel version " << in->major
234 << "." << in->minor << " Expected at least " << FUSE_KERNEL_VERSION
235 << ".6";
236 response.Reset(0, -EPERM, unique);
237 return;
238 }
239
240 // We limit ourselves to minor=15 because we don't handle BATCH_FORGET yet.
241 // Thus we need to use FUSE_COMPAT_22_INIT_OUT_SIZE.
242 #if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
243 // FUSE_KERNEL_VERSION >= 23.
244 const size_t response_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
245 #else
246 const size_t response_size = sizeof(fuse_init_out);
247 #endif
248
249 response.Reset(response_size, kFuseSuccess, unique);
250 fuse_init_out* const out = &response.init_out;
251 out->major = FUSE_KERNEL_VERSION;
252 out->minor = std::min(minor, 15u);
253 out->max_readahead = max_readahead;
254 out->flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
255 out->max_background = 32;
256 out->congestion_threshold = 32;
257 out->max_write = kFuseMaxWrite;
258 }
259
HandleNotImpl()260 void FuseBuffer::HandleNotImpl() {
261 LOG(VERBOSE) << "NOTIMPL op=" << request.header.opcode << " uniq="
262 << request.header.unique << " nid=" << request.header.nodeid;
263 // Add volatile as a workaround for compiler issue which removes the temporary
264 // variable.
265 const volatile uint64_t unique = request.header.unique;
266 response.Reset(0, -ENOSYS, unique);
267 }
268
269 template class FuseMessage<FuseRequest>;
270 template class FuseMessage<FuseResponse>;
271 template class FuseMessage<FuseSimpleResponse>;
272 template struct FuseResponseBase<0u>;
273 template struct FuseResponseBase<kFuseMaxRead>;
274
275 } // namespace fuse
276 } // namespace android
277