blob: 8a333a2f4be6ee366749b06e10fb4115593f3563 [file] [log] [blame]
Mark Salyzyn75b901d2018-05-15 11:19:43 -07001/*
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>
Mark Salyzyn75b901d2018-05-15 11:19:43 -070032#include <android-base/strings.h>
33#include <gtest/gtest.h>
34
35#include "epoll.h"
36
37using namespace std::chrono_literals;
38
39namespace android {
40namespace init {
41
42namespace {
43
44// This class is used to inject keys.
45class EventHandler {
46 public:
47 EventHandler();
48 EventHandler(const EventHandler&) = delete;
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -070049 EventHandler(EventHandler&&) noexcept;
Mark Salyzyn75b901d2018-05-15 11:19:43 -070050 EventHandler& operator=(const EventHandler&) = delete;
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -070051 EventHandler& operator=(EventHandler&&) noexcept;
Mark Salyzyn75b901d2018-05-15 11:19:43 -070052 ~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
64EventHandler::EventHandler() : fd_(-1) {}
65
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -070066EventHandler::EventHandler(EventHandler&& rval) noexcept : fd_(rval.fd_) {
Mark Salyzyn75b901d2018-05-15 11:19:43 -070067 rval.fd_ = -1;
68}
69
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -070070EventHandler& EventHandler::operator=(EventHandler&& rval) noexcept {
Mark Salyzyn75b901d2018-05-15 11:19:43 -070071 fd_ = rval.fd_;
72 rval.fd_ = -1;
73 return *this;
74}
75
76EventHandler::~EventHandler() {
77 if (fd_ == -1) return;
78 ::ioctl(fd_, UI_DEV_DESTROY);
79 ::close(fd_);
80}
81
82bool 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
118bool 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
123bool 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
128bool 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
132std::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
155std::string InitInputFds() {
156 return InitFds("/dev/input/");
157}
158
159std::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
167const std::vector<int> escape_chord = {KEY_ESC};
168const std::vector<int> triple1_chord = {KEY_BACKSPACE, KEY_VOLUMEDOWN, KEY_VOLUMEUP};
169const std::vector<int> triple2_chord = {KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_BACK};
170
171const std::vector<const std::vector<int>> empty_chords;
172const std::vector<const std::vector<int>> chords = {
173 escape_chord,
174 triple1_chord,
175 triple2_chord,
176};
177
178class TestFrame {
179 public:
180 TestFrame(const std::vector<const 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<const std::vector<int>>& chords);
198
199 Epoll epoll_;
200 Keychords keychords_;
201 std::vector<const std::vector<int>> keycodes_;
202 EventHandler* ev_;
203};
204
205TestFrame::TestFrame(const std::vector<const std::vector<int>>& chords, EventHandler* ev)
206 : ev_(ev) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900207 if (!epoll_.Open().ok()) return;
Mark Salyzyn75b901d2018-05-15 11:19:43 -0700208 for (const auto& keycodes : chords) keychords_.Register(keycodes);
209 keychords_.Start(&epoll_, [this](const std::vector<int>& keycodes) {
210 this->keycodes_.emplace_back(keycodes);
211 });
212}
213
214void TestFrame::RelaxForMs(std::chrono::milliseconds wait) {
Tom Cherry905a5df2019-08-30 14:12:56 -0700215 auto pending_functions = epoll_.Wait(wait);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900216 ASSERT_RESULT_OK(pending_functions);
Tom Cherry905a5df2019-08-30 14:12:56 -0700217 for (const auto& function : *pending_functions) {
218 (*function)();
219 }
Mark Salyzyn75b901d2018-05-15 11:19:43 -0700220}
221
222void TestFrame::SetChord(int key, bool value) {
223 ASSERT_TRUE(!!ev_);
224 RelaxForMs();
225 EXPECT_TRUE(ev_->send(key, value));
226}
227
228void TestFrame::SetChords(const std::vector<int>& chord, bool value) {
229 ASSERT_TRUE(!!ev_);
230 for (auto& key : chord) SetChord(key, value);
231 RelaxForMs();
232}
233
234void TestFrame::ClrChord(int key) {
235 ASSERT_TRUE(!!ev_);
236 SetChord(key, false);
237}
238
239void TestFrame::ClrChords(const std::vector<int>& chord) {
240 ASSERT_TRUE(!!ev_);
241 SetChords(chord, false);
242}
243
244bool TestFrame::IsOnlyChord(const std::vector<int>& chord) const {
245 auto ret = false;
246 for (const auto& keycode : keycodes_) {
247 if (keycode != chord) return false;
248 ret = true;
249 }
250 return ret;
251}
252
253bool TestFrame::IsNoChord() const {
254 return keycodes_.empty();
255}
256
257bool TestFrame::IsChord(const std::vector<int>& chord) const {
258 for (const auto& keycode : keycodes_) {
259 if (keycode == chord) return true;
260 }
261 return false;
262}
263
264void TestFrame::WaitForChord(const std::vector<int>& chord) {
265 for (int retry = 1000; retry && !IsChord(chord); --retry) RelaxForMs();
266}
267
268std::string TestFrame::Format(const std::vector<const std::vector<int>>& chords) {
269 std::string ret("{");
270 if (!chords.empty()) {
271 ret += android::base::Join(chords.front(), ' ');
272 for (auto it = std::next(chords.begin()); it != chords.end(); ++it) {
273 ret += ',';
274 ret += android::base::Join(*it, ' ');
275 }
276 }
277 return ret + '}';
278}
279
280std::string TestFrame::Format() const {
281 return Format(keycodes_);
282}
283
284} // namespace
285
286TEST(keychords, not_instantiated) {
287 TestFrame test_frame(empty_chords);
288 EXPECT_TRUE(InitInotifyFds().size() == 0);
289}
290
291TEST(keychords, instantiated) {
292 // Test if a valid set of chords results in proper instantiation of the
293 // underlying mechanisms for /dev/input/ attachment.
294 TestFrame test_frame(chords);
295 EXPECT_TRUE(InitInotifyFds().size() != 0);
296}
297
298TEST(keychords, init_inotify) {
299 std::string before(InitInputFds());
300
301 TestFrame test_frame(chords);
302
303 EventHandler ev;
304 EXPECT_TRUE(ev.init());
305
306 for (int retry = 1000; retry && before == InitInputFds(); --retry) test_frame.RelaxForMs();
307 std::string after(InitInputFds());
308 EXPECT_NE(before, after);
309}
310
311TEST(keychords, key) {
312 EventHandler ev;
313 EXPECT_TRUE(ev.init());
314 TestFrame test_frame(chords, &ev);
315
316 test_frame.SetChords(escape_chord);
317 test_frame.WaitForChord(escape_chord);
318 test_frame.ClrChords(escape_chord);
319 EXPECT_TRUE(test_frame.IsOnlyChord(escape_chord))
320 << "expected only " << android::base::Join(escape_chord, ' ') << " got "
321 << test_frame.Format();
322}
323
324TEST(keychords, keys_in_series) {
325 EventHandler ev;
326 EXPECT_TRUE(ev.init());
327 TestFrame test_frame(chords, &ev);
328
329 for (auto& key : triple1_chord) {
330 test_frame.SetChord(key);
331 test_frame.ClrChord(key);
332 }
333 test_frame.WaitForChord(triple1_chord);
334 EXPECT_TRUE(test_frame.IsNoChord()) << "expected nothing got " << test_frame.Format();
335}
336
337TEST(keychords, keys_in_parallel) {
338 EventHandler ev;
339 EXPECT_TRUE(ev.init());
340 TestFrame test_frame(chords, &ev);
341
342 test_frame.SetChords(triple2_chord);
343 test_frame.WaitForChord(triple2_chord);
344 test_frame.ClrChords(triple2_chord);
345 EXPECT_TRUE(test_frame.IsOnlyChord(triple2_chord))
346 << "expected only " << android::base::Join(triple2_chord, ' ') << " got "
347 << test_frame.Format();
348}
349
350} // namespace init
351} // namespace android