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 epoll_result = epoll_.Wait(wait);
216     ASSERT_RESULT_OK(epoll_result);
217 }
218 
SetChord(int key,bool value)219 void TestFrame::SetChord(int key, bool value) {
220     ASSERT_TRUE(!!ev_);
221     RelaxForMs();
222     EXPECT_TRUE(ev_->send(key, value));
223 }
224 
SetChords(const std::vector<int> & chord,bool value)225 void TestFrame::SetChords(const std::vector<int>& chord, bool value) {
226     ASSERT_TRUE(!!ev_);
227     for (auto& key : chord) SetChord(key, value);
228     RelaxForMs();
229 }
230 
ClrChord(int key)231 void TestFrame::ClrChord(int key) {
232     ASSERT_TRUE(!!ev_);
233     SetChord(key, false);
234 }
235 
ClrChords(const std::vector<int> & chord)236 void TestFrame::ClrChords(const std::vector<int>& chord) {
237     ASSERT_TRUE(!!ev_);
238     SetChords(chord, false);
239 }
240 
IsOnlyChord(const std::vector<int> & chord) const241 bool TestFrame::IsOnlyChord(const std::vector<int>& chord) const {
242     auto ret = false;
243     for (const auto& keycode : keycodes_) {
244         if (keycode != chord) return false;
245         ret = true;
246     }
247     return ret;
248 }
249 
IsNoChord() const250 bool TestFrame::IsNoChord() const {
251     return keycodes_.empty();
252 }
253 
IsChord(const std::vector<int> & chord) const254 bool TestFrame::IsChord(const std::vector<int>& chord) const {
255     for (const auto& keycode : keycodes_) {
256         if (keycode == chord) return true;
257     }
258     return false;
259 }
260 
WaitForChord(const std::vector<int> & chord)261 void TestFrame::WaitForChord(const std::vector<int>& chord) {
262     for (int retry = 1000; retry && !IsChord(chord); --retry) RelaxForMs();
263 }
264 
Format(const std::vector<const std::vector<int>> & chords)265 std::string TestFrame::Format(const std::vector<const std::vector<int>>& chords) {
266     std::string ret("{");
267     if (!chords.empty()) {
268         ret += android::base::Join(chords.front(), ' ');
269         for (auto it = std::next(chords.begin()); it != chords.end(); ++it) {
270             ret += ',';
271             ret += android::base::Join(*it, ' ');
272         }
273     }
274     return ret + '}';
275 }
276 
Format() const277 std::string TestFrame::Format() const {
278     return Format(keycodes_);
279 }
280 
281 }  // namespace
282 
TEST(keychords,not_instantiated)283 TEST(keychords, not_instantiated) {
284     TestFrame test_frame(empty_chords);
285     EXPECT_TRUE(InitInotifyFds().size() == 0);
286 }
287 
TEST(keychords,instantiated)288 TEST(keychords, instantiated) {
289     // Test if a valid set of chords results in proper instantiation of the
290     // underlying mechanisms for /dev/input/ attachment.
291     TestFrame test_frame(chords);
292     EXPECT_TRUE(InitInotifyFds().size() != 0);
293 }
294 
TEST(keychords,init_inotify)295 TEST(keychords, init_inotify) {
296     std::string before(InitInputFds());
297 
298     TestFrame test_frame(chords);
299 
300     EventHandler ev;
301     EXPECT_TRUE(ev.init());
302 
303     for (int retry = 1000; retry && before == InitInputFds(); --retry) test_frame.RelaxForMs();
304     std::string after(InitInputFds());
305     EXPECT_NE(before, after);
306 }
307 
TEST(keychords,key)308 TEST(keychords, key) {
309     EventHandler ev;
310     EXPECT_TRUE(ev.init());
311     TestFrame test_frame(chords, &ev);
312 
313     test_frame.SetChords(escape_chord);
314     test_frame.WaitForChord(escape_chord);
315     test_frame.ClrChords(escape_chord);
316     EXPECT_TRUE(test_frame.IsOnlyChord(escape_chord))
317         << "expected only " << android::base::Join(escape_chord, ' ') << " got "
318         << test_frame.Format();
319 }
320 
TEST(keychords,keys_in_series)321 TEST(keychords, keys_in_series) {
322     EventHandler ev;
323     EXPECT_TRUE(ev.init());
324     TestFrame test_frame(chords, &ev);
325 
326     for (auto& key : triple1_chord) {
327         test_frame.SetChord(key);
328         test_frame.ClrChord(key);
329     }
330     test_frame.WaitForChord(triple1_chord);
331     EXPECT_TRUE(test_frame.IsNoChord()) << "expected nothing got " << test_frame.Format();
332 }
333 
TEST(keychords,keys_in_parallel)334 TEST(keychords, keys_in_parallel) {
335     EventHandler ev;
336     EXPECT_TRUE(ev.init());
337     TestFrame test_frame(chords, &ev);
338 
339     test_frame.SetChords(triple2_chord);
340     test_frame.WaitForChord(triple2_chord);
341     test_frame.ClrChords(triple2_chord);
342     EXPECT_TRUE(test_frame.IsOnlyChord(triple2_chord))
343         << "expected only " << android::base::Join(triple2_chord, ' ') << " got "
344         << test_frame.Format();
345 }
346 
347 }  // namespace init
348 }  // namespace android
349