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 #ifndef ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
18 #define ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
19 
20 #include <map>
21 #include <mutex>
22 #include <queue>
23 #include <unordered_set>
24 
25 #include <android-base/macros.h>
26 
27 #include "libappfuse/FuseBuffer.h"
28 
29 namespace android {
30 namespace fuse {
31 
32 class FuseBridgeLoopCallback {
33  public:
34    virtual void OnMount(int mount_id) = 0;
35    virtual void OnClosed(int mount_id) = 0;
36    virtual ~FuseBridgeLoopCallback() = default;
37 };
38 
39 class FuseBridgeEntry;
40 class BridgeEpollController;
41 
42 class FuseBridgeLoop final {
43   public:
44     FuseBridgeLoop();
45     ~FuseBridgeLoop();
46 
47     void Start(FuseBridgeLoopCallback* callback);
48 
49     // Add bridge to the loop. It's OK to invoke the method from a different
50     // thread from one which invokes |Start|.
51     bool AddBridge(int mount_id, base::unique_fd dev_fd, base::unique_fd proxy_fd);
52 
53     static void Lock();
54 
55     static void Unlock();
56 
57   private:
58     bool ProcessEventLocked(const std::unordered_set<FuseBridgeEntry*>& entries,
59                             FuseBridgeLoopCallback* callback);
60 
61     std::unique_ptr<BridgeEpollController> epoll_controller_;
62 
63     // Map between |mount_id| and bridge entry.
64     std::map<int, std::unique_ptr<FuseBridgeEntry>> bridges_;
65 
66     // Lock for multi-threading.
67     static std::recursive_mutex mutex_;
68 
69     bool opened_;
70 
71     DISALLOW_COPY_AND_ASSIGN(FuseBridgeLoop);
72 };
73 
74 }  // namespace fuse
75 }  // namespace android
76 
77 #endif  // ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
78