1 //
2 //  Copyright (C) 2015 Google, Inc.
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 specific language governing permissions and
14 //  limitations under the License.
15 //
16 
17 #pragma once
18 
19 #include <atomic>
20 
21 #include <base/files/file_path.h>
22 #include <base/files/scoped_file.h>
23 #include <base/macros.h>
24 #include <base/threading/thread.h>
25 
26 #include "service/ipc/ipc_handler.h"
27 #include "service/ipc/ipc_manager.h"
28 
29 namespace base {
30 class SingleThreadTaskRunner;
31 }  // namespace base
32 
33 namespace ipc {
34 
35 // Implements a Linux sequential packet domain-socket based IPCHandler
36 class IPCHandlerLinux : public IPCHandler {
37  public:
38   IPCHandlerLinux(bluetooth::Adapter* adapter, IPCManager::Delegate* delegate);
39   ~IPCHandlerLinux() override;
40 
41   // IPCHandler overrides:
42   bool Run() override;
43   void Stop() override;
44 
45  private:
46   IPCHandlerLinux() = default;
47 
48   // Starts listening for incoming connections. Posted on |thread_| by Run().
49   void StartListeningOnThread();
50 
51   // Stops the IPC thread. This helper is needed since base::Thread requires
52   // threads to be stopped on the thread that started them.
53   void ShutDownOnOriginThread();
54 
55   // Notifies the delegate that we started or stoppedlistening for incoming
56   // connections.
57   void NotifyStartedOnOriginThread();
58   void NotifyStartedOnCurrentThread();
59   void NotifyStoppedOnOriginThread();
60   void NotifyStoppedOnCurrentThread();
61 
62 // True, if the IPC mechanism is running.
63 #if defined(__APPLE__)
64   bool running_ ATTRIBUTE_UNUSED;
65 #else
66   bool running_;
67 #endif
68 
69   // The server socket on which we listen to incoming connections.
70   base::ScopedFD socket_;
71 
72   // The file path to |socket_|. This is only set if we create and manage the
73   // life time of the socket.
74   base::FilePath socket_path_;
75 
76   // We use a dedicated thread for listening to incoming connections and
77   // polling from the socket to avoid blocking the main thread.
78   base::Thread thread_;
79 
80   // Whether or not the listening thread should continue to run.
81   std::atomic<bool> keep_running_;
82 
83   // The origin thread's task runner.
84   scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner_;
85 
86   DISALLOW_COPY_AND_ASSIGN(IPCHandlerLinux);
87 };
88 
89 }  // namespace ipc
90