1 /*
2 * Copyright (C) 2018 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 "keychords.h"
18
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <linux/input.h>
22 #include <linux/uinput.h>
23 #include <stdint.h>
24 #include <sys/types.h>
25
26 #include <chrono>
27 #include <set>
28 #include <string>
29 #include <vector>
30
31 #include <android-base/properties.h>
32 #include <android-base/strings.h>
33 #include <gtest/gtest.h>
34
35 #include "epoll.h"
36
37 using namespace std::chrono_literals;
38
39 namespace android {
40 namespace init {
41
42 namespace {
43
44 // This class is used to inject keys.
45 class EventHandler {
46 public:
47 EventHandler();
48 EventHandler(const EventHandler&) = delete;
49 EventHandler(EventHandler&&) noexcept;
50 EventHandler& operator=(const EventHandler&) = delete;
51 EventHandler& operator=(EventHandler&&) noexcept;
52 ~EventHandler() noexcept;
53
54 bool init();
55
56 bool send(struct input_event& e);
57 bool send(uint16_t type, uint16_t code, uint16_t value);
58 bool send(uint16_t code, bool value);
59
60 private:
61 int fd_;
62 };
63
EventHandler()64 EventHandler::EventHandler() : fd_(-1) {}
65
EventHandler(EventHandler && rval)66 EventHandler::EventHandler(EventHandler&& rval) noexcept : fd_(rval.fd_) {
67 rval.fd_ = -1;
68 }
69
operator =(EventHandler && rval)70 EventHandler& EventHandler::operator=(EventHandler&& rval) noexcept {
71 fd_ = rval.fd_;
72 rval.fd_ = -1;
73 return *this;
74 }
75
~EventHandler()76 EventHandler::~EventHandler() {
77 if (fd_ == -1) return;
78 ::ioctl(fd_, UI_DEV_DESTROY);
79 ::close(fd_);
80 }
81
init()82 bool EventHandler::init() {
83 if (fd_ != -1) return true;
84 auto fd = TEMP_FAILURE_RETRY(::open("/dev/uinput", O_WRONLY | O_NONBLOCK | O_CLOEXEC));
85 if (fd == -1) return false;
86 if (::ioctl(fd, UI_SET_EVBIT, EV_KEY) == -1) {
87 ::close(fd);
88 return false;
89 }
90
91 static const struct uinput_user_dev u = {
92 .name = "com.google.android.init.test",
93 .id.bustype = BUS_VIRTUAL,
94 .id.vendor = 0x1AE0, // Google
95 .id.product = 0x494E, // IN
96 .id.version = 1,
97 };
98 if (TEMP_FAILURE_RETRY(::write(fd, &u, sizeof(u))) != sizeof(u)) {
99 ::close(fd);
100 return false;
101 }
102
103 // all keys
104 for (uint16_t i = 0; i < KEY_MAX; ++i) {
105 if (::ioctl(fd, UI_SET_KEYBIT, i) == -1) {
106 ::close(fd);
107 return false;
108 }
109 }
110 if (::ioctl(fd, UI_DEV_CREATE) == -1) {
111 ::close(fd);
112 return false;
113 }
114 fd_ = fd;
115 return true;
116 }
117
send(struct input_event & e)118 bool EventHandler::send(struct input_event& e) {
119 gettimeofday(&e.time, nullptr);
120 return TEMP_FAILURE_RETRY(::write(fd_, &e, sizeof(e))) == sizeof(e);
121 }
122
send(uint16_t type,uint16_t code,uint16_t value)123 bool EventHandler::send(uint16_t type, uint16_t code, uint16_t value) {
124 struct input_event e = {.type = type, .code = code, .value = value};
125 return send(e);
126 }
127
send(uint16_t code,bool value)128 bool EventHandler::send(uint16_t code, bool value) {
129 return (code < KEY_MAX) && init() && send(EV_KEY, code, value) && send(EV_SYN, SYN_REPORT, 0);
130 }
131
InitFds(const char * prefix,pid_t pid=getpid ())132 std::string InitFds(const char* prefix, pid_t pid = getpid()) {
133 std::string ret;
134
135 std::string init_fds("/proc/");
136 init_fds += std::to_string(pid) + "/fd";
137 std::unique_ptr<DIR, decltype(&closedir)> fds(opendir(init_fds.c_str()), closedir);
138 if (!fds) return ret;
139
140 dirent* entry;
141 while ((entry = readdir(fds.get()))) {
142 if (entry->d_name[0] == '.') continue;
143 std::string devname = init_fds + '/' + entry->d_name;
144 char buf[256];
145 auto retval = readlink(devname.c_str(), buf, sizeof(buf) - 1);
146 if ((retval < 0) || (size_t(retval) >= (sizeof(buf) - 1))) continue;
147 buf[retval] = '\0';
148 if (!android::base::StartsWith(buf, prefix)) continue;
149 if (ret.size() != 0) ret += ",";
150 ret += buf;
151 }
152 return ret;
153 }
154
InitInputFds()155 std::string InitInputFds() {
156 return InitFds("/dev/input/");
157 }
158
InitInotifyFds()159 std::string InitInotifyFds() {
160 return InitFds("anon_inode:inotify");
161 }
162
163 // NB: caller (this series of tests, or conversely the service parser in init)
164 // is responsible for validation, sorting and uniqueness of the chords, so no
165 // fuzzing is advised.
166
167 const std::vector<int> escape_chord = {KEY_ESC};
168 const std::vector<int> triple1_chord = {KEY_BACKSPACE, KEY_VOLUMEDOWN, KEY_VOLUMEUP};
169 const std::vector<int> triple2_chord = {KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_BACK};
170
171 const std::vector<std::vector<int>> empty_chords;
172 const std::vector<std::vector<int>> chords = {
173 escape_chord,
174 triple1_chord,
175 triple2_chord,
176 };
177
178 class TestFrame {
179 public:
180 TestFrame(const std::vector<std::vector<int>>& chords, EventHandler* ev = nullptr);
181
182 void RelaxForMs(std::chrono::milliseconds wait = 1ms);
183
184 void SetChord(int key, bool value = true);
185 void SetChords(const std::vector<int>& chord, bool value = true);
186 void ClrChord(int key);
187 void ClrChords(const std::vector<int>& chord);
188
189 bool IsOnlyChord(const std::vector<int>& chord) const;
190 bool IsNoChord() const;
191 bool IsChord(const std::vector<int>& chord) const;
192 void WaitForChord(const std::vector<int>& chord);
193
194 std::string Format() const;
195
196 private:
197 static std::string Format(const std::vector<std::vector<int>>& chords);
198
199 Epoll epoll_;
200 Keychords keychords_;
201 std::vector<std::vector<int>> keycodes_;
202 EventHandler* ev_;
203 };
204
TestFrame(const std::vector<std::vector<int>> & chords,EventHandler * ev)205 TestFrame::TestFrame(const std::vector<std::vector<int>>& chords, EventHandler* ev) : ev_(ev) {
206 if (!epoll_.Open().ok()) return;
207 for (const auto& keycodes : chords) keychords_.Register(keycodes);
208 keychords_.Start(&epoll_, [this](const std::vector<int>& keycodes) {
209 this->keycodes_.emplace_back(keycodes);
210 });
211 }
212
RelaxForMs(std::chrono::milliseconds wait)213 void TestFrame::RelaxForMs(std::chrono::milliseconds wait) {
214 auto epoll_result = epoll_.Wait(wait);
215 ASSERT_RESULT_OK(epoll_result);
216 }
217
SetChord(int key,bool value)218 void TestFrame::SetChord(int key, bool value) {
219 ASSERT_TRUE(!!ev_);
220 RelaxForMs();
221 EXPECT_TRUE(ev_->send(key, value));
222 }
223
SetChords(const std::vector<int> & chord,bool value)224 void TestFrame::SetChords(const std::vector<int>& chord, bool value) {
225 ASSERT_TRUE(!!ev_);
226 for (auto& key : chord) SetChord(key, value);
227 RelaxForMs();
228 }
229
ClrChord(int key)230 void TestFrame::ClrChord(int key) {
231 ASSERT_TRUE(!!ev_);
232 SetChord(key, false);
233 }
234
ClrChords(const std::vector<int> & chord)235 void TestFrame::ClrChords(const std::vector<int>& chord) {
236 ASSERT_TRUE(!!ev_);
237 SetChords(chord, false);
238 }
239
IsOnlyChord(const std::vector<int> & chord) const240 bool TestFrame::IsOnlyChord(const std::vector<int>& chord) const {
241 auto ret = false;
242 for (const auto& keycode : keycodes_) {
243 if (keycode != chord) return false;
244 ret = true;
245 }
246 return ret;
247 }
248
IsNoChord() const249 bool TestFrame::IsNoChord() const {
250 return keycodes_.empty();
251 }
252
IsChord(const std::vector<int> & chord) const253 bool TestFrame::IsChord(const std::vector<int>& chord) const {
254 for (const auto& keycode : keycodes_) {
255 if (keycode == chord) return true;
256 }
257 return false;
258 }
259
WaitForChord(const std::vector<int> & chord)260 void TestFrame::WaitForChord(const std::vector<int>& chord) {
261 for (int retry = 1000; retry && !IsChord(chord); --retry) RelaxForMs();
262 }
263
Format(const std::vector<std::vector<int>> & chords)264 std::string TestFrame::Format(const std::vector<std::vector<int>>& chords) {
265 std::string ret("{");
266 if (!chords.empty()) {
267 ret += android::base::Join(chords.front(), ' ');
268 for (auto it = std::next(chords.begin()); it != chords.end(); ++it) {
269 ret += ',';
270 ret += android::base::Join(*it, ' ');
271 }
272 }
273 return ret + '}';
274 }
275
Format() const276 std::string TestFrame::Format() const {
277 return Format(keycodes_);
278 }
279
280 } // namespace
281
TEST(keychords,not_instantiated)282 TEST(keychords, not_instantiated) {
283 TestFrame test_frame(empty_chords);
284 EXPECT_TRUE(InitInotifyFds().size() == 0);
285 }
286
TEST(keychords,instantiated)287 TEST(keychords, instantiated) {
288 // Test if a valid set of chords results in proper instantiation of the
289 // underlying mechanisms for /dev/input/ attachment.
290 TestFrame test_frame(chords);
291 EXPECT_TRUE(InitInotifyFds().size() != 0);
292 }
293
TEST(keychords,init_inotify)294 TEST(keychords, init_inotify) {
295 std::string before(InitInputFds());
296
297 TestFrame test_frame(chords);
298
299 EventHandler ev;
300 EXPECT_TRUE(ev.init());
301
302 for (int retry = 1000; retry && before == InitInputFds(); --retry) test_frame.RelaxForMs();
303 std::string after(InitInputFds());
304 EXPECT_NE(before, after);
305 }
306
TEST(keychords,key)307 TEST(keychords, key) {
308 EventHandler ev;
309 EXPECT_TRUE(ev.init());
310 TestFrame test_frame(chords, &ev);
311
312 test_frame.SetChords(escape_chord);
313 test_frame.WaitForChord(escape_chord);
314 test_frame.ClrChords(escape_chord);
315 EXPECT_TRUE(test_frame.IsOnlyChord(escape_chord))
316 << "expected only " << android::base::Join(escape_chord, ' ') << " got "
317 << test_frame.Format();
318 }
319
TEST(keychords,keys_in_series)320 TEST(keychords, keys_in_series) {
321 EventHandler ev;
322 EXPECT_TRUE(ev.init());
323 TestFrame test_frame(chords, &ev);
324
325 for (auto& key : triple1_chord) {
326 test_frame.SetChord(key);
327 test_frame.ClrChord(key);
328 }
329 test_frame.WaitForChord(triple1_chord);
330 EXPECT_TRUE(test_frame.IsNoChord()) << "expected nothing got " << test_frame.Format();
331 }
332
TEST(keychords,keys_in_parallel)333 TEST(keychords, keys_in_parallel) {
334 EventHandler ev;
335 EXPECT_TRUE(ev.init());
336 TestFrame test_frame(chords, &ev);
337
338 test_frame.SetChords(triple2_chord);
339 test_frame.WaitForChord(triple2_chord);
340 test_frame.ClrChords(triple2_chord);
341 EXPECT_TRUE(test_frame.IsOnlyChord(triple2_chord))
342 << "expected only " << android::base::Join(triple2_chord, ' ') << " got "
343 << test_frame.Format();
344 }
345
346 } // namespace init
347 } // namespace android
348