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<const std::vector<int>> empty_chords;
172 const std::vector<const 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<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
TestFrame(const std::vector<const std::vector<int>> & chords,EventHandler * ev)205 TestFrame::TestFrame(const std::vector<const std::vector<int>>& chords, EventHandler* ev)
206 : ev_(ev) {
207 if (!epoll_.Open().ok()) return;
208 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
RelaxForMs(std::chrono::milliseconds wait)214 void TestFrame::RelaxForMs(std::chrono::milliseconds wait) {
215 auto pending_functions = epoll_.Wait(wait);
216 ASSERT_RESULT_OK(pending_functions);
217 for (const auto& function : *pending_functions) {
218 (*function)();
219 }
220 }
221
SetChord(int key,bool value)222 void TestFrame::SetChord(int key, bool value) {
223 ASSERT_TRUE(!!ev_);
224 RelaxForMs();
225 EXPECT_TRUE(ev_->send(key, value));
226 }
227
SetChords(const std::vector<int> & chord,bool value)228 void 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
ClrChord(int key)234 void TestFrame::ClrChord(int key) {
235 ASSERT_TRUE(!!ev_);
236 SetChord(key, false);
237 }
238
ClrChords(const std::vector<int> & chord)239 void TestFrame::ClrChords(const std::vector<int>& chord) {
240 ASSERT_TRUE(!!ev_);
241 SetChords(chord, false);
242 }
243
IsOnlyChord(const std::vector<int> & chord) const244 bool 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
IsNoChord() const253 bool TestFrame::IsNoChord() const {
254 return keycodes_.empty();
255 }
256
IsChord(const std::vector<int> & chord) const257 bool 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
WaitForChord(const std::vector<int> & chord)264 void TestFrame::WaitForChord(const std::vector<int>& chord) {
265 for (int retry = 1000; retry && !IsChord(chord); --retry) RelaxForMs();
266 }
267
Format(const std::vector<const std::vector<int>> & chords)268 std::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
Format() const280 std::string TestFrame::Format() const {
281 return Format(keycodes_);
282 }
283
284 } // namespace
285
TEST(keychords,not_instantiated)286 TEST(keychords, not_instantiated) {
287 TestFrame test_frame(empty_chords);
288 EXPECT_TRUE(InitInotifyFds().size() == 0);
289 }
290
TEST(keychords,instantiated)291 TEST(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
TEST(keychords,init_inotify)298 TEST(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
TEST(keychords,key)311 TEST(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
TEST(keychords,keys_in_series)324 TEST(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
TEST(keychords,keys_in_parallel)337 TEST(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
352