blob: 07923071b39b1cc62296db5b13473977b7a3f289 [file] [log] [blame]
Daichi Hironoc6134762016-10-27 14:57:55 +09001/*
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/FuseBridgeLoop.h"
18
Daichi Hirono96c6aa42017-03-06 15:37:20 +090019#include <sys/epoll.h>
20#include <sys/socket.h>
21
22#include <unordered_map>
23
Daichi Hironoc6134762016-10-27 14:57:55 +090024#include <android-base/logging.h>
25#include <android-base/unique_fd.h>
26
Daichi Hirono96c6aa42017-03-06 15:37:20 +090027#include "libappfuse/EpollController.h"
28
Daichi Hironoc6134762016-10-27 14:57:55 +090029namespace android {
Daichi Hirono691739b2016-11-15 15:42:05 +090030namespace fuse {
Daichi Hirono96c6aa42017-03-06 15:37:20 +090031namespace {
Daichi Hironoc6134762016-10-27 14:57:55 +090032
Daichi Hirono96c6aa42017-03-06 15:37:20 +090033enum class FuseBridgeState { kWaitToReadEither, kWaitToReadProxy, kWaitToWriteProxy, kClosing };
Daichi Hironoc6134762016-10-27 14:57:55 +090034
Daichi Hirono96c6aa42017-03-06 15:37:20 +090035struct FuseBridgeEntryEvent {
36 FuseBridgeEntry* entry;
37 int events;
38};
39
40void GetObservedEvents(FuseBridgeState state, int* device_events, int* proxy_events) {
41 switch (state) {
42 case FuseBridgeState::kWaitToReadEither:
43 *device_events = EPOLLIN;
44 *proxy_events = EPOLLIN;
45 return;
46 case FuseBridgeState::kWaitToReadProxy:
47 *device_events = 0;
48 *proxy_events = EPOLLIN;
49 return;
50 case FuseBridgeState::kWaitToWriteProxy:
51 *device_events = 0;
52 *proxy_events = EPOLLOUT;
53 return;
54 case FuseBridgeState::kClosing:
55 *device_events = 0;
56 *proxy_events = 0;
57 return;
58 }
59}
Daichi Hironoe5a15562017-06-09 13:12:21 +090060
61void LogResponseError(const std::string& message, const FuseResponse& response) {
62 LOG(ERROR) << message << ": header.len=" << response.header.len
63 << " header.error=" << response.header.error
64 << " header.unique=" << response.header.unique;
65}
Daichi Hirono96c6aa42017-03-06 15:37:20 +090066}
67
68class FuseBridgeEntry {
69 public:
70 FuseBridgeEntry(int mount_id, base::unique_fd&& dev_fd, base::unique_fd&& proxy_fd)
71 : mount_id_(mount_id),
72 device_fd_(std::move(dev_fd)),
73 proxy_fd_(std::move(proxy_fd)),
74 state_(FuseBridgeState::kWaitToReadEither),
75 last_state_(FuseBridgeState::kWaitToReadEither),
76 last_device_events_({this, 0}),
77 last_proxy_events_({this, 0}),
78 open_count_(0) {}
79
80 // Transfer bytes depends on availability of FDs and the internal |state_|.
81 void Transfer(FuseBridgeLoopCallback* callback) {
82 constexpr int kUnexpectedEventMask = ~(EPOLLIN | EPOLLOUT);
83 const bool unexpected_event = (last_device_events_.events & kUnexpectedEventMask) ||
84 (last_proxy_events_.events & kUnexpectedEventMask);
85 const bool device_read_ready = last_device_events_.events & EPOLLIN;
86 const bool proxy_read_ready = last_proxy_events_.events & EPOLLIN;
87 const bool proxy_write_ready = last_proxy_events_.events & EPOLLOUT;
88
89 last_device_events_.events = 0;
90 last_proxy_events_.events = 0;
91
92 LOG(VERBOSE) << "Transfer device_read_ready=" << device_read_ready
93 << " proxy_read_ready=" << proxy_read_ready
94 << " proxy_write_ready=" << proxy_write_ready;
95
96 if (unexpected_event) {
97 LOG(ERROR) << "Invalid epoll event is observed";
98 state_ = FuseBridgeState::kClosing;
99 return;
100 }
101
102 switch (state_) {
103 case FuseBridgeState::kWaitToReadEither:
104 if (proxy_read_ready) {
105 state_ = ReadFromProxy();
106 } else if (device_read_ready) {
107 state_ = ReadFromDevice(callback);
108 }
109 return;
110
111 case FuseBridgeState::kWaitToReadProxy:
112 CHECK(proxy_read_ready);
113 state_ = ReadFromProxy();
114 return;
115
116 case FuseBridgeState::kWaitToWriteProxy:
117 CHECK(proxy_write_ready);
118 state_ = WriteToProxy();
119 return;
120
121 case FuseBridgeState::kClosing:
122 return;
123 }
Daichi Hironoc6134762016-10-27 14:57:55 +0900124 }
125
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900126 bool IsClosing() const { return state_ == FuseBridgeState::kClosing; }
Daichi Hironoc6134762016-10-27 14:57:55 +0900127
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900128 int mount_id() const { return mount_id_; }
129
130 private:
131 friend class BridgeEpollController;
132
133 FuseBridgeState ReadFromProxy() {
134 switch (buffer_.response.ReadOrAgain(proxy_fd_)) {
135 case ResultOrAgain::kSuccess:
136 break;
137 case ResultOrAgain::kFailure:
138 return FuseBridgeState::kClosing;
139 case ResultOrAgain::kAgain:
140 return FuseBridgeState::kWaitToReadProxy;
Daichi Hironoc6134762016-10-27 14:57:55 +0900141 }
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900142
143 if (!buffer_.response.Write(device_fd_)) {
Daichi Hironoe5a15562017-06-09 13:12:21 +0900144 LogResponseError("Failed to write a reply from proxy to device", buffer_.response);
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900145 return FuseBridgeState::kClosing;
Daichi Hironoc6134762016-10-27 14:57:55 +0900146 }
Daichi Hironoc6134762016-10-27 14:57:55 +0900147
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900148 auto it = opcode_map_.find(buffer_.response.header.unique);
149 if (it != opcode_map_.end()) {
150 switch (it->second) {
151 case FUSE_OPEN:
152 if (buffer_.response.header.error == fuse::kFuseSuccess) {
153 open_count_++;
154 }
155 break;
Daichi Hironoc6134762016-10-27 14:57:55 +0900156
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900157 case FUSE_RELEASE:
158 if (open_count_ > 0) {
159 open_count_--;
160 } else {
161 LOG(WARNING) << "Unexpected FUSE_RELEASE before opening a file.";
162 break;
163 }
164 if (open_count_ == 0) {
165 return FuseBridgeState::kClosing;
166 }
167 break;
168 }
169 opcode_map_.erase(it);
170 }
171
172 return FuseBridgeState::kWaitToReadEither;
Daichi Hironoc6134762016-10-27 14:57:55 +0900173 }
174
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900175 FuseBridgeState ReadFromDevice(FuseBridgeLoopCallback* callback) {
176 LOG(VERBOSE) << "ReadFromDevice";
177 if (!buffer_.request.Read(device_fd_)) {
178 return FuseBridgeState::kClosing;
179 }
180
181 const uint32_t opcode = buffer_.request.header.opcode;
182 LOG(VERBOSE) << "Read a fuse packet, opcode=" << opcode;
183 switch (opcode) {
184 case FUSE_FORGET:
185 // Do not reply to FUSE_FORGET.
186 return FuseBridgeState::kWaitToReadEither;
187
188 case FUSE_LOOKUP:
189 case FUSE_GETATTR:
190 case FUSE_OPEN:
191 case FUSE_READ:
192 case FUSE_WRITE:
193 case FUSE_RELEASE:
194 case FUSE_FSYNC:
195 if (opcode == FUSE_OPEN || opcode == FUSE_RELEASE) {
196 opcode_map_.emplace(buffer_.request.header.unique, opcode);
197 }
198 return WriteToProxy();
199
200 case FUSE_INIT:
201 buffer_.HandleInit();
202 break;
203
204 default:
205 buffer_.HandleNotImpl();
206 break;
207 }
208
209 if (!buffer_.response.Write(device_fd_)) {
Daichi Hironoe5a15562017-06-09 13:12:21 +0900210 LogResponseError("Failed to write a response to device", buffer_.response);
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900211 return FuseBridgeState::kClosing;
212 }
213
214 if (opcode == FUSE_INIT) {
215 callback->OnMount(mount_id_);
216 }
217
218 return FuseBridgeState::kWaitToReadEither;
Daichi Hironoc6134762016-10-27 14:57:55 +0900219 }
220
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900221 FuseBridgeState WriteToProxy() {
222 switch (buffer_.request.WriteOrAgain(proxy_fd_)) {
223 case ResultOrAgain::kSuccess:
224 return FuseBridgeState::kWaitToReadEither;
225 case ResultOrAgain::kFailure:
Daichi Hironoe5a15562017-06-09 13:12:21 +0900226 LOG(ERROR) << "Failed to write a request to proxy:"
227 << " header.len=" << buffer_.request.header.len
228 << " header.opcode=" << buffer_.request.header.opcode
229 << " header.unique=" << buffer_.request.header.unique
230 << " header.nodeid=" << buffer_.request.header.nodeid;
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900231 return FuseBridgeState::kClosing;
232 case ResultOrAgain::kAgain:
233 return FuseBridgeState::kWaitToWriteProxy;
Daichi Hirono30e68082016-11-15 09:31:21 +0900234 }
Daichi Hironoc6134762016-10-27 14:57:55 +0900235 }
Daichi Hirono96c6aa42017-03-06 15:37:20 +0900236
237 const int mount_id_;
238 base::unique_fd device_fd_;
239 base::unique_fd proxy_fd_;
240 FuseBuffer buffer_;
241 FuseBridgeState state_;
242 FuseBridgeState last_state_;
243 FuseBridgeEntryEvent last_device_events_;
244 FuseBridgeEntryEvent last_proxy_events_;
245
246 // Remember map between unique and opcode in fuse_in_header so that we can
247 // refer the opcode later.
248 std::unordered_map<uint64_t, uint32_t> opcode_map_;
249
250 int open_count_;
251
252 DISALLOW_COPY_AND_ASSIGN(FuseBridgeEntry);
253};
254
255class BridgeEpollController : private EpollController {
256 public:
257 BridgeEpollController(base::unique_fd&& poll_fd) : EpollController(std::move(poll_fd)) {}
258
259 bool AddBridgePoll(FuseBridgeEntry* bridge) const {
260 return InvokeControl(EPOLL_CTL_ADD, bridge);
261 }
262
263 bool UpdateOrDeleteBridgePoll(FuseBridgeEntry* bridge) const {
264 return InvokeControl(
265 bridge->state_ != FuseBridgeState::kClosing ? EPOLL_CTL_MOD : EPOLL_CTL_DEL, bridge);
266 }
267
268 bool Wait(size_t bridge_count, std::unordered_set<FuseBridgeEntry*>* entries_out) {
269 CHECK(entries_out);
270 const size_t event_count = std::max<size_t>(bridge_count * 2, 1);
271 if (!EpollController::Wait(event_count)) {
272 return false;
273 }
274 entries_out->clear();
275 for (const auto& event : events()) {
276 FuseBridgeEntryEvent* const entry_event =
277 reinterpret_cast<FuseBridgeEntryEvent*>(event.data.ptr);
278 entry_event->events = event.events;
279 entries_out->insert(entry_event->entry);
280 }
281 return true;
282 }
283
284 private:
285 bool InvokeControl(int op, FuseBridgeEntry* bridge) const {
286 LOG(VERBOSE) << "InvokeControl op=" << op << " bridge=" << bridge->mount_id_
287 << " state=" << static_cast<int>(bridge->state_)
288 << " last_state=" << static_cast<int>(bridge->last_state_);
289
290 int last_device_events;
291 int last_proxy_events;
292 int device_events;
293 int proxy_events;
294 GetObservedEvents(bridge->last_state_, &last_device_events, &last_proxy_events);
295 GetObservedEvents(bridge->state_, &device_events, &proxy_events);
296 bool result = true;
297 if (op != EPOLL_CTL_MOD || last_device_events != device_events) {
298 result &= EpollController::InvokeControl(op, bridge->device_fd_, device_events,
299 &bridge->last_device_events_);
300 }
301 if (op != EPOLL_CTL_MOD || last_proxy_events != proxy_events) {
302 result &= EpollController::InvokeControl(op, bridge->proxy_fd_, proxy_events,
303 &bridge->last_proxy_events_);
304 }
305 return result;
306 }
307};
308
309FuseBridgeLoop::FuseBridgeLoop() : opened_(true) {
310 base::unique_fd epoll_fd(epoll_create1(/* no flag */ 0));
311 if (epoll_fd.get() == -1) {
312 PLOG(ERROR) << "Failed to open FD for epoll";
313 opened_ = false;
314 return;
315 }
316 epoll_controller_.reset(new BridgeEpollController(std::move(epoll_fd)));
317}
318
319FuseBridgeLoop::~FuseBridgeLoop() { CHECK(bridges_.empty()); }
320
321bool FuseBridgeLoop::AddBridge(int mount_id, base::unique_fd dev_fd, base::unique_fd proxy_fd) {
322 LOG(VERBOSE) << "Adding bridge " << mount_id;
323
324 std::unique_ptr<FuseBridgeEntry> bridge(
325 new FuseBridgeEntry(mount_id, std::move(dev_fd), std::move(proxy_fd)));
326 std::lock_guard<std::mutex> lock(mutex_);
327 if (!opened_) {
328 LOG(ERROR) << "Tried to add a mount to a closed bridge";
329 return false;
330 }
331 if (bridges_.count(mount_id)) {
332 LOG(ERROR) << "Tried to add a mount point that has already been added";
333 return false;
334 }
335 if (!epoll_controller_->AddBridgePoll(bridge.get())) {
336 return false;
337 }
338
339 bridges_.emplace(mount_id, std::move(bridge));
340 return true;
341}
342
343bool FuseBridgeLoop::ProcessEventLocked(const std::unordered_set<FuseBridgeEntry*>& entries,
344 FuseBridgeLoopCallback* callback) {
345 for (auto entry : entries) {
346 entry->Transfer(callback);
347 if (!epoll_controller_->UpdateOrDeleteBridgePoll(entry)) {
348 return false;
349 }
350 if (entry->IsClosing()) {
351 const int mount_id = entry->mount_id();
352 callback->OnClosed(mount_id);
353 bridges_.erase(mount_id);
354 if (bridges_.size() == 0) {
355 // All bridges are now closed.
356 return false;
357 }
358 }
359 }
360 return true;
361}
362
363void FuseBridgeLoop::Start(FuseBridgeLoopCallback* callback) {
364 LOG(DEBUG) << "Start fuse bridge loop";
365 std::unordered_set<FuseBridgeEntry*> entries;
366 while (true) {
367 const bool wait_result = epoll_controller_->Wait(bridges_.size(), &entries);
368 LOG(VERBOSE) << "Receive epoll events";
369 {
370 std::lock_guard<std::mutex> lock(mutex_);
371 if (!(wait_result && ProcessEventLocked(entries, callback))) {
372 for (auto it = bridges_.begin(); it != bridges_.end();) {
373 callback->OnClosed(it->second->mount_id());
374 it = bridges_.erase(it);
375 }
376 opened_ = false;
377 return;
378 }
379 }
380 }
Daichi Hironoc6134762016-10-27 14:57:55 +0900381}
382
Daichi Hironoa0aecda2016-11-08 10:17:51 +0900383} // namespace fuse
Daichi Hironoc6134762016-10-27 14:57:55 +0900384} // namespace android