1 /*
2 * Copyright (C) 2017 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 specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "ConnectionDetector.h"
18
19 #include <utils/Log.h>
20
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <netinet/in.h>
24 #include <sys/inotify.h>
25 #include <sys/socket.h>
26
27 #include <sstream>
28
29 namespace android {
30 namespace SensorHalExt {
31
32 // SocketConnectionDetector functions
SocketConnectionDetector(BaseDynamicSensorDaemon * d,int port)33 SocketConnectionDetector::SocketConnectionDetector(BaseDynamicSensorDaemon *d, int port)
34 : ConnectionDetector(d), Thread(false /*canCallJava*/) {
35 // initialize socket that accept connection to localhost:port
36 mListenFd = ::socket(AF_INET, SOCK_STREAM, 0);
37 if (mListenFd < 0) {
38 ALOGE("Cannot open socket");
39 return;
40 }
41
42 struct sockaddr_in serverAddress = {
43 .sin_family = AF_INET,
44 .sin_port = htons(port),
45 .sin_addr = {
46 .s_addr = htonl(INADDR_LOOPBACK)
47 }
48 };
49
50 ::bind(mListenFd, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
51 if (::listen(mListenFd, 0) != NO_ERROR) {
52 ALOGE("Cannot listen to port %d", port);
53 mListenFd = -1;
54 return;
55 }
56
57 std::ostringstream s;
58 s << "socket:" << port;
59 mDevice = s.str();
60 }
61
~SocketConnectionDetector()62 SocketConnectionDetector::~SocketConnectionDetector() {
63 if (mListenFd >= 0) {
64 requestExitAndWait();
65 }
66 }
67
Init()68 void SocketConnectionDetector::Init() {
69 // run adds a strong reference to this object, so it can't be invoked from
70 // the constructor.
71 run("ddad_socket");
72 }
73
waitForConnection()74 int SocketConnectionDetector::waitForConnection() {
75 return ::accept(mListenFd, nullptr, nullptr);
76 }
77
waitForDisconnection(int connFd)78 void SocketConnectionDetector::waitForDisconnection(int connFd) {
79 char buffer[16];
80 while (::read(connFd, buffer, sizeof(buffer)) > 0) {
81 // discard data but response something to denote thread alive
82 ::write(connFd, ".", 1);
83 }
84 // read failure means disconnection
85 ::close(connFd);
86 }
87
threadLoop()88 bool SocketConnectionDetector::threadLoop() {
89 while (!Thread::exitPending()) {
90 // block waiting for connection
91 int connFd = waitForConnection();
92
93 if (connFd < 0) {
94 break;
95 }
96
97 ALOGV("Received connection, register dynamic accel sensor");
98 mDaemon->onConnectionChange(mDevice, true);
99
100 waitForDisconnection(connFd);
101 ALOGV("Connection break, unregister dynamic accel sensor");
102 mDaemon->onConnectionChange(mDevice, false);
103 }
104 mDaemon->onConnectionChange(mDevice, false);
105 ALOGD("SocketConnectionDetector thread exited");
106 return false;
107 }
108
109 // FileConnectionDetector functions
FileConnectionDetector(BaseDynamicSensorDaemon * d,const std::string & path,const std::string & regex)110 FileConnectionDetector::FileConnectionDetector (
111 BaseDynamicSensorDaemon *d, const std::string &path, const std::string ®ex)
112 : ConnectionDetector(d), Thread(false /*callCallJava*/), mPath(path), mRegex(regex),
113 mLooper(new Looper(true /*allowNonCallback*/)), mInotifyFd(-1) {
114 if (mLooper == nullptr) {
115 return;
116 }
117
118 mInotifyFd = ::inotify_init1(IN_NONBLOCK);
119 if (mInotifyFd < 0) {
120 ALOGE("Cannot init inotify");
121 return;
122 }
123
124 int wd = ::inotify_add_watch(mInotifyFd, path.c_str(), IN_CREATE | IN_DELETE);
125 if (wd < 0 || !mLooper->addFd(mInotifyFd, POLL_IDENT, Looper::EVENT_INPUT, nullptr, nullptr)) {
126 ::close(mInotifyFd);
127 mInotifyFd = -1;
128 ALOGE("Cannot setup watch on dir %s", path.c_str());
129 return;
130 }
131 }
132
~FileConnectionDetector()133 FileConnectionDetector::~FileConnectionDetector() {
134 if (mInotifyFd > 0) {
135 requestExit();
136 mLooper->wake();
137 join();
138 ::close(mInotifyFd);
139 }
140 }
141
Init()142 void FileConnectionDetector::Init() {
143 // mLooper != null && mInotifyFd added to looper
144 // run adds a strong reference to this object, so it can't be invoked from
145 // the constructor.
146 run("ddad_file");
147 }
148
matches(const std::string & name) const149 bool FileConnectionDetector::matches(const std::string &name) const {
150 return std::regex_match(name, mRegex);
151 }
152
getFullName(const std::string name) const153 std::string FileConnectionDetector::getFullName(const std::string name) const {
154 return mPath + name;
155 }
156
processExistingFiles() const157 void FileConnectionDetector::processExistingFiles() const {
158 auto dirp = ::opendir(mPath.c_str());
159 if(dirp == NULL) {
160 ALOGE("Problem open dir %s, errno: %s", mPath.c_str(), ::strerror(errno));
161 return;
162 }
163 struct dirent *dp;
164 while ((dp = ::readdir(dirp)) != NULL) {
165 const std::string name(dp->d_name);
166 if (matches(name)) {
167 mDaemon->onConnectionChange(getFullName(name), true /*connected*/);
168 }
169 }
170 ::closedir(dirp);
171 }
172
handleInotifyData(ssize_t len,const char * data)173 void FileConnectionDetector::handleInotifyData(ssize_t len, const char *data) {
174 const char *dataEnd = data + len;
175 const struct inotify_event *ev;
176
177 // inotify adds paddings to guarantee the next read is aligned
178 for (; data < dataEnd; data += sizeof(struct inotify_event) + ev->len) {
179 ev = reinterpret_cast<const struct inotify_event*>(data);
180 if (ev->mask & IN_ISDIR) {
181 continue;
182 }
183
184 const std::string name(ev->name);
185 if (matches(name)) {
186 if (ev->mask & IN_CREATE) {
187 mDaemon->onConnectionChange(getFullName(name), true /*connected*/);
188 }
189 if (ev->mask & IN_DELETE) {
190 mDaemon->onConnectionChange(getFullName(name), false /*connected*/);
191 }
192 }
193 }
194 }
195
readInotifyData()196 bool FileConnectionDetector::readInotifyData() {
197 union {
198 struct inotify_event ev;
199 char raw[sizeof(inotify_event) + NAME_MAX + 1];
200 } buffer;
201
202 bool ret = true;
203 while (true) {
204 ssize_t len = ::read(mInotifyFd, &buffer, sizeof(buffer));
205 if (len == -1 && errno == EAGAIN) {
206 // no more data
207 break;
208 } else if (len > static_cast<ssize_t>(sizeof(struct inotify_event))) {
209 handleInotifyData(len, reinterpret_cast<char*>(&buffer));
210 } else if (len < 0) {
211 ALOGE("read error: %s", ::strerror(errno));
212 ret = false;
213 break;
214 } else {
215 // 0 <= len <= sizeof(struct inotify_event)
216 ALOGE("read return %zd, shorter than inotify_event size %zu",
217 len, sizeof(struct inotify_event));
218 ret = false;
219 break;
220 }
221 }
222 return ret;
223 }
224
threadLoop()225 bool FileConnectionDetector::threadLoop() {
226 Looper::setForThread(mLooper);
227 processExistingFiles();
228 while(!Thread::exitPending()) {
229 int ret = mLooper->pollOnce(-1);
230
231 if (ret != Looper::POLL_WAKE && ret != POLL_IDENT) {
232 ALOGE("Unexpected value %d from pollOnce, quit", ret);
233 requestExit();
234 break;
235 }
236
237 if (ret == POLL_IDENT) {
238 if (!readInotifyData()) {
239 requestExit();
240 }
241 }
242 }
243
244 mLooper->removeFd(mInotifyFd);
245 ALOGD("FileConnectionDetection thread exited");
246 return false;
247 }
248
249 } // namespace SensorHalExt
250 } // namespace android
251