• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 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 <assert.h>
18 #include <dirent.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <memory.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/capability.h>
28 #include <sys/epoll.h>
29 #include <sys/inotify.h>
30 #include <sys/ioctl.h>
31 #include <sys/limits.h>
32 #include <sys/stat.h>
33 #include <sys/sysmacros.h>
34 #include <unistd.h>
35 
36 #define LOG_TAG "EventHub"
37 
38 // #define LOG_NDEBUG 0
39 #include <android-base/file.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/strings.h>
42 #include <cutils/properties.h>
43 #include <ftl/enum.h>
44 #include <input/KeyCharacterMap.h>
45 #include <input/KeyLayoutMap.h>
46 #include <input/VirtualKeyMap.h>
47 #include <openssl/sha.h>
48 #include <statslog.h>
49 #include <utils/Errors.h>
50 #include <utils/Log.h>
51 #include <utils/Timers.h>
52 
53 #include <filesystem>
54 #include <regex>
55 
56 #include "EventHub.h"
57 
58 #define INDENT "  "
59 #define INDENT2 "    "
60 #define INDENT3 "      "
61 
62 using android::base::StringPrintf;
63 
64 namespace android {
65 
66 using namespace ftl::flag_operators;
67 
68 static const char* DEVICE_INPUT_PATH = "/dev/input";
69 // v4l2 devices go directly into /dev
70 static const char* DEVICE_PATH = "/dev";
71 
72 static constexpr size_t OBFUSCATED_LENGTH = 8;
73 
74 static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
75 static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
76 
77 // Mapping for input battery class node IDs lookup.
78 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
79 static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
80         {{"capacity", InputBatteryClass::CAPACITY},
81          {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
82          {"status", InputBatteryClass::STATUS}};
83 
84 // Mapping for input battery class node names lookup.
85 // https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
86 static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
87         {{InputBatteryClass::CAPACITY, "capacity"},
88          {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
89          {InputBatteryClass::STATUS, "status"}};
90 
91 // must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
92 static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
93         {{"Unknown", BATTERY_STATUS_UNKNOWN},
94          {"Charging", BATTERY_STATUS_CHARGING},
95          {"Discharging", BATTERY_STATUS_DISCHARGING},
96          {"Not charging", BATTERY_STATUS_NOT_CHARGING},
97          {"Full", BATTERY_STATUS_FULL}};
98 
99 // Mapping taken from
100 // https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
101 static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
102                                                                        {"Low", 10},
103                                                                        {"Normal", 55},
104                                                                        {"High", 70},
105                                                                        {"Full", 100},
106                                                                        {"Unknown", 50}};
107 
108 // Mapping for input led class node names lookup.
109 // https://www.kernel.org/doc/html/latest/leds/leds-class.html
110 static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
111         {{"red", InputLightClass::RED},
112          {"green", InputLightClass::GREEN},
113          {"blue", InputLightClass::BLUE},
114          {"global", InputLightClass::GLOBAL},
115          {"brightness", InputLightClass::BRIGHTNESS},
116          {"multi_index", InputLightClass::MULTI_INDEX},
117          {"multi_intensity", InputLightClass::MULTI_INTENSITY},
118          {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
119 
120 // Mapping for input multicolor led class node names.
121 // https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
122 static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
123         {{InputLightClass::BRIGHTNESS, "brightness"},
124          {InputLightClass::MULTI_INDEX, "multi_index"},
125          {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
126 
127 // Mapping for light color name and the light color
128 const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
129                                                                   {"green", LightColor::GREEN},
130                                                                   {"blue", LightColor::BLUE}};
131 
toString(bool value)132 static inline const char* toString(bool value) {
133     return value ? "true" : "false";
134 }
135 
sha1(const std::string & in)136 static std::string sha1(const std::string& in) {
137     SHA_CTX ctx;
138     SHA1_Init(&ctx);
139     SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
140     u_char digest[SHA_DIGEST_LENGTH];
141     SHA1_Final(digest, &ctx);
142 
143     std::string out;
144     for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
145         out += StringPrintf("%02x", digest[i]);
146     }
147     return out;
148 }
149 
150 /**
151  * Return true if name matches "v4l-touch*"
152  */
isV4lTouchNode(std::string name)153 static bool isV4lTouchNode(std::string name) {
154     return name.find("v4l-touch") != std::string::npos;
155 }
156 
157 /**
158  * Returns true if V4L devices should be scanned.
159  *
160  * The system property ro.input.video_enabled can be used to control whether
161  * EventHub scans and opens V4L devices. As V4L does not support multiple
162  * clients, EventHub effectively blocks access to these devices when it opens
163  * them.
164  *
165  * Setting this to "false" would prevent any video devices from being discovered and
166  * associated with input devices.
167  *
168  * This property can be used as follows:
169  * 1. To turn off features that are dependent on video device presence.
170  * 2. During testing and development, to allow other clients to read video devices
171  * directly from /dev.
172  */
isV4lScanningEnabled()173 static bool isV4lScanningEnabled() {
174     return property_get_bool("ro.input.video_enabled", true /* default_value */);
175 }
176 
processEventTimestamp(const struct input_event & event)177 static nsecs_t processEventTimestamp(const struct input_event& event) {
178     // Use the time specified in the event instead of the current time
179     // so that downstream code can get more accurate estimates of
180     // event dispatch latency from the time the event is enqueued onto
181     // the evdev client buffer.
182     //
183     // The event's timestamp fortuitously uses the same monotonic clock
184     // time base as the rest of Android. The kernel event device driver
185     // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
186     // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
187     // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
188     // system call that also queries ktime_get_ts().
189 
190     const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
191             microseconds_to_nanoseconds(event.time.tv_usec);
192     return inputEventTime;
193 }
194 
195 /**
196  * Returns the sysfs root path of the input device
197  *
198  */
getSysfsRootPath(const char * devicePath)199 static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
200     std::error_code errorCode;
201 
202     // Stat the device path to get the major and minor number of the character file
203     struct stat statbuf;
204     if (stat(devicePath, &statbuf) == -1) {
205         ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
206         return std::nullopt;
207     }
208 
209     unsigned int major_num = major(statbuf.st_rdev);
210     unsigned int minor_num = minor(statbuf.st_rdev);
211 
212     // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
213     auto sysfsPath = std::filesystem::path("/sys/dev/char/");
214     sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
215     sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
216 
217     // Make sure nothing went wrong in call to canonical()
218     if (errorCode) {
219         ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
220               errorCode.message().c_str());
221         return std::nullopt;
222     }
223 
224     // Continue to go up a directory until we reach a directory named "input"
225     while (sysfsPath != "/" && sysfsPath.filename() != "input") {
226         sysfsPath = sysfsPath.parent_path();
227     }
228 
229     // Then go up one more and you will be at the sysfs root of the device
230     sysfsPath = sysfsPath.parent_path();
231 
232     // Make sure we didn't reach root path and that directory actually exists
233     if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
234         if (errorCode) {
235             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
236                   errorCode.message().c_str());
237         }
238 
239         // Not found
240         return std::nullopt;
241     }
242 
243     return sysfsPath;
244 }
245 
246 /**
247  * Returns the list of files under a specified path.
248  */
allFilesInPath(const std::filesystem::path & path)249 static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
250     std::vector<std::filesystem::path> nodes;
251     std::error_code errorCode;
252     auto iter = std::filesystem::directory_iterator(path, errorCode);
253     while (!errorCode && iter != std::filesystem::directory_iterator()) {
254         nodes.push_back(iter->path());
255         iter++;
256     }
257     return nodes;
258 }
259 
260 /**
261  * Returns the list of files under a specified directory in a sysfs path.
262  * Example:
263  * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
264  * in the sysfs path.
265  */
findSysfsNodes(const std::filesystem::path & sysfsRoot,SysfsClass clazz)266 static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
267                                                          SysfsClass clazz) {
268     std::string nodeStr = ftl::enum_string(clazz);
269     std::for_each(nodeStr.begin(), nodeStr.end(),
270                   [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
271     std::vector<std::filesystem::path> nodes;
272     for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
273         nodes = allFilesInPath(path / nodeStr);
274     }
275     return nodes;
276 }
277 
getColorIndexArray(std::filesystem::path path)278 static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
279         std::filesystem::path path) {
280     std::string indexStr;
281     if (!base::ReadFileToString(path, &indexStr)) {
282         return std::nullopt;
283     }
284 
285     // Parse the multi color LED index file, refer to kernel docs
286     // leds/leds-class-multicolor.html
287     std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
288     std::smatch results;
289     std::array<LightColor, COLOR_NUM> colors;
290     if (!std::regex_match(indexStr, results, indexPattern)) {
291         return std::nullopt;
292     }
293 
294     for (size_t i = 1; i < results.size(); i++) {
295         const auto it = LIGHT_COLORS.find(results[i].str());
296         if (it != LIGHT_COLORS.end()) {
297             // intensities.emplace(it->second, 0);
298             colors[i - 1] = it->second;
299         }
300     }
301     return colors;
302 }
303 
304 // --- Global Functions ---
305 
getAbsAxisUsage(int32_t axis,ftl::Flags<InputDeviceClass> deviceClasses)306 ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
307                                              ftl::Flags<InputDeviceClass> deviceClasses) {
308     // Touch devices get dibs on touch-related axes.
309     if (deviceClasses.test(InputDeviceClass::TOUCH)) {
310         switch (axis) {
311             case ABS_X:
312             case ABS_Y:
313             case ABS_PRESSURE:
314             case ABS_TOOL_WIDTH:
315             case ABS_DISTANCE:
316             case ABS_TILT_X:
317             case ABS_TILT_Y:
318             case ABS_MT_SLOT:
319             case ABS_MT_TOUCH_MAJOR:
320             case ABS_MT_TOUCH_MINOR:
321             case ABS_MT_WIDTH_MAJOR:
322             case ABS_MT_WIDTH_MINOR:
323             case ABS_MT_ORIENTATION:
324             case ABS_MT_POSITION_X:
325             case ABS_MT_POSITION_Y:
326             case ABS_MT_TOOL_TYPE:
327             case ABS_MT_BLOB_ID:
328             case ABS_MT_TRACKING_ID:
329             case ABS_MT_PRESSURE:
330             case ABS_MT_DISTANCE:
331                 return InputDeviceClass::TOUCH;
332         }
333     }
334 
335     if (deviceClasses.test(InputDeviceClass::SENSOR)) {
336         switch (axis) {
337             case ABS_X:
338             case ABS_Y:
339             case ABS_Z:
340             case ABS_RX:
341             case ABS_RY:
342             case ABS_RZ:
343                 return InputDeviceClass::SENSOR;
344         }
345     }
346 
347     // External stylus gets the pressure axis
348     if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
349         if (axis == ABS_PRESSURE) {
350             return InputDeviceClass::EXTERNAL_STYLUS;
351         }
352     }
353 
354     // Joystick devices get the rest.
355     return deviceClasses & InputDeviceClass::JOYSTICK;
356 }
357 
358 // --- EventHub::Device ---
359 
Device(int fd,int32_t id,const std::string & path,const InputDeviceIdentifier & identifier)360 EventHub::Device::Device(int fd, int32_t id, const std::string& path,
361                          const InputDeviceIdentifier& identifier)
362       : fd(fd),
363         id(id),
364         path(path),
365         identifier(identifier),
366         classes(0),
367         configuration(nullptr),
368         virtualKeyMap(nullptr),
369         ffEffectPlaying(false),
370         ffEffectId(-1),
371         associatedDevice(nullptr),
372         controllerNumber(0),
373         enabled(true),
374         isVirtual(fd < 0) {}
375 
~Device()376 EventHub::Device::~Device() {
377     close();
378 }
379 
close()380 void EventHub::Device::close() {
381     if (fd >= 0) {
382         ::close(fd);
383         fd = -1;
384     }
385 }
386 
enable()387 status_t EventHub::Device::enable() {
388     fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
389     if (fd < 0) {
390         ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
391         return -errno;
392     }
393     enabled = true;
394     return OK;
395 }
396 
disable()397 status_t EventHub::Device::disable() {
398     close();
399     enabled = false;
400     return OK;
401 }
402 
hasValidFd() const403 bool EventHub::Device::hasValidFd() const {
404     return !isVirtual && enabled;
405 }
406 
getKeyCharacterMap() const407 const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
408     return keyMap.keyCharacterMap;
409 }
410 
411 template <std::size_t N>
readDeviceBitMask(unsigned long ioctlCode,BitArray<N> & bitArray)412 status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
413     if (!hasValidFd()) {
414         return BAD_VALUE;
415     }
416     if ((_IOC_SIZE(ioctlCode) == 0)) {
417         ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
418     }
419 
420     typename BitArray<N>::Buffer buffer;
421     status_t ret = ioctl(fd, ioctlCode, buffer.data());
422     bitArray.loadFromBuffer(buffer);
423     return ret;
424 }
425 
configureFd()426 void EventHub::Device::configureFd() {
427     // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
428     if (classes.test(InputDeviceClass::KEYBOARD)) {
429         // Disable kernel key repeat since we handle it ourselves
430         unsigned int repeatRate[] = {0, 0};
431         if (ioctl(fd, EVIOCSREP, repeatRate)) {
432             ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
433         }
434     }
435 
436     // Tell the kernel that we want to use the monotonic clock for reporting timestamps
437     // associated with input events.  This is important because the input system
438     // uses the timestamps extensively and assumes they were recorded using the monotonic
439     // clock.
440     int clockId = CLOCK_MONOTONIC;
441     if (classes.test(InputDeviceClass::SENSOR)) {
442         // Each new sensor event should use the same time base as
443         // SystemClock.elapsedRealtimeNanos().
444         clockId = CLOCK_BOOTTIME;
445     }
446     bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
447     ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
448 }
449 
hasKeycodeLocked(int keycode) const450 bool EventHub::Device::hasKeycodeLocked(int keycode) const {
451     if (!keyMap.haveKeyLayout()) {
452         return false;
453     }
454 
455     std::vector<int32_t> scanCodes;
456     keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
457     const size_t N = scanCodes.size();
458     for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
459         int32_t sc = scanCodes[i];
460         if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
461             return true;
462         }
463     }
464 
465     return false;
466 }
467 
loadConfigurationLocked()468 void EventHub::Device::loadConfigurationLocked() {
469     configurationFile =
470             getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
471                                                                   InputDeviceConfigurationFileType::
472                                                                           CONFIGURATION);
473     if (configurationFile.empty()) {
474         ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
475     } else {
476         android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
477                 PropertyMap::load(configurationFile.c_str());
478         if (!propertyMap.ok()) {
479             ALOGE("Error loading input device configuration file for device '%s'.  "
480                   "Using default configuration.",
481                   identifier.name.c_str());
482         } else {
483             configuration = std::move(*propertyMap);
484         }
485     }
486 }
487 
loadVirtualKeyMapLocked()488 bool EventHub::Device::loadVirtualKeyMapLocked() {
489     // The virtual key map is supplied by the kernel as a system board property file.
490     std::string propPath = "/sys/board_properties/virtualkeys.";
491     propPath += identifier.getCanonicalName();
492     if (access(propPath.c_str(), R_OK)) {
493         return false;
494     }
495     virtualKeyMap = VirtualKeyMap::load(propPath);
496     return virtualKeyMap != nullptr;
497 }
498 
loadKeyMapLocked()499 status_t EventHub::Device::loadKeyMapLocked() {
500     return keyMap.load(identifier, configuration.get());
501 }
502 
isExternalDeviceLocked()503 bool EventHub::Device::isExternalDeviceLocked() {
504     if (configuration) {
505         bool value;
506         if (configuration->tryGetProperty(String8("device.internal"), value)) {
507             return !value;
508         }
509     }
510     return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
511 }
512 
deviceHasMicLocked()513 bool EventHub::Device::deviceHasMicLocked() {
514     if (configuration) {
515         bool value;
516         if (configuration->tryGetProperty(String8("audio.mic"), value)) {
517             return value;
518         }
519     }
520     return false;
521 }
522 
setLedStateLocked(int32_t led,bool on)523 void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
524     int32_t sc;
525     if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
526         struct input_event ev;
527         ev.time.tv_sec = 0;
528         ev.time.tv_usec = 0;
529         ev.type = EV_LED;
530         ev.code = sc;
531         ev.value = on ? 1 : 0;
532 
533         ssize_t nWrite;
534         do {
535             nWrite = write(fd, &ev, sizeof(struct input_event));
536         } while (nWrite == -1 && errno == EINTR);
537     }
538 }
539 
setLedForControllerLocked()540 void EventHub::Device::setLedForControllerLocked() {
541     for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
542         setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
543     }
544 }
545 
mapLed(int32_t led,int32_t * outScanCode) const546 status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
547     if (!keyMap.haveKeyLayout()) {
548         return NAME_NOT_FOUND;
549     }
550 
551     int32_t scanCode;
552     if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
553         if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
554             *outScanCode = scanCode;
555             return NO_ERROR;
556         }
557     }
558     return NAME_NOT_FOUND;
559 }
560 
561 // Check the sysfs path for any input device batteries, returns true if battery found.
configureBatteryLocked()562 bool EventHub::AssociatedDevice::configureBatteryLocked() {
563     nextBatteryId = 0;
564     // Check if device has any battery.
565     const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
566     for (const auto& nodePath : paths) {
567         RawBatteryInfo info;
568         info.id = ++nextBatteryId;
569         info.path = nodePath;
570         info.name = nodePath.filename();
571 
572         // Scan the path for all the files
573         // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
574         const auto& files = allFilesInPath(nodePath);
575         for (const auto& file : files) {
576             const auto it = BATTERY_CLASSES.find(file.filename().string());
577             if (it != BATTERY_CLASSES.end()) {
578                 info.flags |= it->second;
579             }
580         }
581         batteryInfos.insert_or_assign(info.id, info);
582         ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
583     }
584     return !batteryInfos.empty();
585 }
586 
587 // Check the sysfs path for any input device lights, returns true if lights found.
configureLightsLocked()588 bool EventHub::AssociatedDevice::configureLightsLocked() {
589     nextLightId = 0;
590     // Check if device has any lights.
591     const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
592     for (const auto& nodePath : paths) {
593         RawLightInfo info;
594         info.id = ++nextLightId;
595         info.path = nodePath;
596         info.name = nodePath.filename();
597         info.maxBrightness = std::nullopt;
598         size_t nameStart = info.name.rfind(":");
599         if (nameStart != std::string::npos) {
600             // Trim the name to color name
601             info.name = info.name.substr(nameStart + 1);
602             // Set InputLightClass flag for colors
603             const auto it = LIGHT_CLASSES.find(info.name);
604             if (it != LIGHT_CLASSES.end()) {
605                 info.flags |= it->second;
606             }
607         }
608         // Scan the path for all the files
609         // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
610         const auto& files = allFilesInPath(nodePath);
611         for (const auto& file : files) {
612             const auto it = LIGHT_CLASSES.find(file.filename().string());
613             if (it != LIGHT_CLASSES.end()) {
614                 info.flags |= it->second;
615                 // If the node has maximum brightness, read it
616                 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
617                     std::string str;
618                     if (base::ReadFileToString(file, &str)) {
619                         info.maxBrightness = std::stoi(str);
620                     }
621                 }
622             }
623         }
624         lightInfos.insert_or_assign(info.id, info);
625         ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
626     }
627     return !lightInfos.empty();
628 }
629 
630 /**
631  * Get the capabilities for the current process.
632  * Crashes the system if unable to create / check / destroy the capabilities object.
633  */
634 class Capabilities final {
635 public:
Capabilities()636     explicit Capabilities() {
637         mCaps = cap_get_proc();
638         LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
639     }
640 
641     /**
642      * Check whether the current process has a specific capability
643      * in the set of effective capabilities.
644      * Return CAP_SET if the process has the requested capability
645      * Return CAP_CLEAR otherwise.
646      */
checkEffectiveCapability(cap_value_t capability)647     cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
648         cap_flag_value_t value;
649         const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
650         LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
651         return value;
652     }
653 
~Capabilities()654     ~Capabilities() {
655         const int result = cap_free(mCaps);
656         LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
657     }
658 
659 private:
660     cap_t mCaps;
661 };
662 
ensureProcessCanBlockSuspend()663 static void ensureProcessCanBlockSuspend() {
664     Capabilities capabilities;
665     const bool canBlockSuspend =
666             capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
667     LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
668                         "Input must be able to block suspend to properly process events");
669 }
670 
671 // --- EventHub ---
672 
673 const int EventHub::EPOLL_MAX_EVENTS;
674 
EventHub(void)675 EventHub::EventHub(void)
676       : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
677         mNextDeviceId(1),
678         mControllerNumbers(),
679         mNeedToSendFinishedDeviceScan(false),
680         mNeedToReopenDevices(false),
681         mNeedToScanDevices(true),
682         mPendingEventCount(0),
683         mPendingEventIndex(0),
684         mPendingINotify(false) {
685     ensureProcessCanBlockSuspend();
686 
687     mEpollFd = epoll_create1(EPOLL_CLOEXEC);
688     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
689 
690     mINotifyFd = inotify_init1(IN_CLOEXEC);
691 
692     std::error_code errorCode;
693     bool isDeviceInotifyAdded = false;
694     if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
695         addDeviceInputInotify();
696     } else {
697         addDeviceInotify();
698         isDeviceInotifyAdded = true;
699         if (errorCode) {
700             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
701                   errorCode.message().c_str());
702         }
703     }
704 
705     if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
706         addDeviceInotify();
707     } else {
708         ALOGI("Video device scanning disabled");
709     }
710 
711     struct epoll_event eventItem = {};
712     eventItem.events = EPOLLIN | EPOLLWAKEUP;
713     eventItem.data.fd = mINotifyFd;
714     int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
715     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance.  errno=%d", errno);
716 
717     int wakeFds[2];
718     result = pipe2(wakeFds, O_CLOEXEC);
719     LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);
720 
721     mWakeReadPipeFd = wakeFds[0];
722     mWakeWritePipeFd = wakeFds[1];
723 
724     result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
725     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",
726                         errno);
727 
728     result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
729     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",
730                         errno);
731 
732     eventItem.data.fd = mWakeReadPipeFd;
733     result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
734     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",
735                         errno);
736 }
737 
~EventHub(void)738 EventHub::~EventHub(void) {
739     closeAllDevicesLocked();
740 
741     ::close(mEpollFd);
742     ::close(mINotifyFd);
743     ::close(mWakeReadPipeFd);
744     ::close(mWakeWritePipeFd);
745 }
746 
747 /**
748  * On devices that don't have any input devices (like some development boards), the /dev/input
749  * directory will be absent. However, the user may still plug in an input device at a later time.
750  * Add watch for contents of /dev/input only when /dev/input appears.
751  */
addDeviceInputInotify()752 void EventHub::addDeviceInputInotify() {
753     mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
754     LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
755                         DEVICE_INPUT_PATH, strerror(errno));
756 }
757 
addDeviceInotify()758 void EventHub::addDeviceInotify() {
759     mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
760     LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
761                         strerror(errno));
762 }
763 
getDeviceIdentifier(int32_t deviceId) const764 InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
765     std::scoped_lock _l(mLock);
766     Device* device = getDeviceLocked(deviceId);
767     return device != nullptr ? device->identifier : InputDeviceIdentifier();
768 }
769 
getDeviceClasses(int32_t deviceId) const770 ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
771     std::scoped_lock _l(mLock);
772     Device* device = getDeviceLocked(deviceId);
773     return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
774 }
775 
getDeviceControllerNumber(int32_t deviceId) const776 int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
777     std::scoped_lock _l(mLock);
778     Device* device = getDeviceLocked(deviceId);
779     return device != nullptr ? device->controllerNumber : 0;
780 }
781 
getConfiguration(int32_t deviceId,PropertyMap * outConfiguration) const782 void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
783     std::scoped_lock _l(mLock);
784     Device* device = getDeviceLocked(deviceId);
785     if (device != nullptr && device->configuration) {
786         *outConfiguration = *device->configuration;
787     } else {
788         outConfiguration->clear();
789     }
790 }
791 
getAbsoluteAxisInfo(int32_t deviceId,int axis,RawAbsoluteAxisInfo * outAxisInfo) const792 status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
793                                        RawAbsoluteAxisInfo* outAxisInfo) const {
794     outAxisInfo->clear();
795 
796     if (axis >= 0 && axis <= ABS_MAX) {
797         std::scoped_lock _l(mLock);
798 
799         Device* device = getDeviceLocked(deviceId);
800         if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
801             struct input_absinfo info;
802             if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
803                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
804                       device->identifier.name.c_str(), device->fd, errno);
805                 return -errno;
806             }
807 
808             if (info.minimum != info.maximum) {
809                 outAxisInfo->valid = true;
810                 outAxisInfo->minValue = info.minimum;
811                 outAxisInfo->maxValue = info.maximum;
812                 outAxisInfo->flat = info.flat;
813                 outAxisInfo->fuzz = info.fuzz;
814                 outAxisInfo->resolution = info.resolution;
815             }
816             return OK;
817         }
818     }
819     return -1;
820 }
821 
hasRelativeAxis(int32_t deviceId,int axis) const822 bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
823     if (axis >= 0 && axis <= REL_MAX) {
824         std::scoped_lock _l(mLock);
825         Device* device = getDeviceLocked(deviceId);
826         return device != nullptr ? device->relBitmask.test(axis) : false;
827     }
828     return false;
829 }
830 
hasInputProperty(int32_t deviceId,int property) const831 bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
832     std::scoped_lock _l(mLock);
833 
834     Device* device = getDeviceLocked(deviceId);
835     return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
836             ? device->propBitmask.test(property)
837             : false;
838 }
839 
hasMscEvent(int32_t deviceId,int mscEvent) const840 bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
841     std::scoped_lock _l(mLock);
842 
843     Device* device = getDeviceLocked(deviceId);
844     return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
845             ? device->mscBitmask.test(mscEvent)
846             : false;
847 }
848 
getScanCodeState(int32_t deviceId,int32_t scanCode) const849 int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
850     if (scanCode >= 0 && scanCode <= KEY_MAX) {
851         std::scoped_lock _l(mLock);
852 
853         Device* device = getDeviceLocked(deviceId);
854         if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
855             if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
856                 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
857             }
858         }
859     }
860     return AKEY_STATE_UNKNOWN;
861 }
862 
getKeyCodeState(int32_t deviceId,int32_t keyCode) const863 int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
864     std::scoped_lock _l(mLock);
865 
866     Device* device = getDeviceLocked(deviceId);
867     if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
868         std::vector<int32_t> scanCodes;
869         device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
870         if (scanCodes.size() != 0) {
871             if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
872                 for (size_t i = 0; i < scanCodes.size(); i++) {
873                     int32_t sc = scanCodes[i];
874                     if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
875                         return AKEY_STATE_DOWN;
876                     }
877                 }
878                 return AKEY_STATE_UP;
879             }
880         }
881     }
882     return AKEY_STATE_UNKNOWN;
883 }
884 
getKeyCodeForKeyLocation(int32_t deviceId,int32_t locationKeyCode) const885 int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
886     std::scoped_lock _l(mLock);
887 
888     Device* device = getDeviceLocked(deviceId);
889     if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
890         device->keyMap.keyLayoutMap == nullptr) {
891         return AKEYCODE_UNKNOWN;
892     }
893     std::vector<int32_t> scanCodes;
894     device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode, &scanCodes);
895     if (scanCodes.empty()) {
896         ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
897               "device %d",
898               locationKeyCode, deviceId);
899         return AKEYCODE_UNKNOWN;
900     }
901     if (scanCodes.size() > 1) {
902         ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
903               locationKeyCode);
904     }
905     int32_t outKeyCode;
906     status_t mapKeyRes =
907             device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
908     switch (mapKeyRes) {
909         case OK:
910             return outKeyCode;
911         case NAME_NOT_FOUND:
912             // key character map doesn't re-map this scanCode, hence the keyCode remains the same
913             return locationKeyCode;
914         default:
915             ALOGW("Failed to get key code for key location: Key character map returned error %s",
916                   statusToString(mapKeyRes).c_str());
917             return AKEYCODE_UNKNOWN;
918     }
919 }
920 
getSwitchState(int32_t deviceId,int32_t sw) const921 int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
922     if (sw >= 0 && sw <= SW_MAX) {
923         std::scoped_lock _l(mLock);
924 
925         Device* device = getDeviceLocked(deviceId);
926         if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
927             if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
928                 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
929             }
930         }
931     }
932     return AKEY_STATE_UNKNOWN;
933 }
934 
getAbsoluteAxisValue(int32_t deviceId,int32_t axis,int32_t * outValue) const935 status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
936     *outValue = 0;
937 
938     if (axis >= 0 && axis <= ABS_MAX) {
939         std::scoped_lock _l(mLock);
940 
941         Device* device = getDeviceLocked(deviceId);
942         if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
943             struct input_absinfo info;
944             if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
945                 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
946                       device->identifier.name.c_str(), device->fd, errno);
947                 return -errno;
948             }
949 
950             *outValue = info.value;
951             return OK;
952         }
953     }
954     return -1;
955 }
956 
markSupportedKeyCodes(int32_t deviceId,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags) const957 bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
958                                      uint8_t* outFlags) const {
959     std::scoped_lock _l(mLock);
960 
961     Device* device = getDeviceLocked(deviceId);
962     if (device != nullptr && device->keyMap.haveKeyLayout()) {
963         std::vector<int32_t> scanCodes;
964         for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
965             scanCodes.clear();
966 
967             status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
968                                                                             &scanCodes);
969             if (!err) {
970                 // check the possible scan codes identified by the layout map against the
971                 // map of codes actually emitted by the driver
972                 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
973                     if (device->keyBitmask.test(scanCodes[sc])) {
974                         outFlags[codeIndex] = 1;
975                         break;
976                     }
977                 }
978             }
979         }
980         return true;
981     }
982     return false;
983 }
984 
mapKey(int32_t deviceId,int32_t scanCode,int32_t usageCode,int32_t metaState,int32_t * outKeycode,int32_t * outMetaState,uint32_t * outFlags) const985 status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
986                           int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
987     std::scoped_lock _l(mLock);
988     Device* device = getDeviceLocked(deviceId);
989     status_t status = NAME_NOT_FOUND;
990 
991     if (device != nullptr) {
992         // Check the key character map first.
993         const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
994         if (kcm) {
995             if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
996                 *outFlags = 0;
997                 status = NO_ERROR;
998             }
999         }
1000 
1001         // Check the key layout next.
1002         if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
1003             if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
1004                 status = NO_ERROR;
1005             }
1006         }
1007 
1008         if (status == NO_ERROR) {
1009             if (kcm) {
1010                 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1011             } else {
1012                 *outMetaState = metaState;
1013             }
1014         }
1015     }
1016 
1017     if (status != NO_ERROR) {
1018         *outKeycode = 0;
1019         *outFlags = 0;
1020         *outMetaState = metaState;
1021     }
1022 
1023     return status;
1024 }
1025 
mapAxis(int32_t deviceId,int32_t scanCode,AxisInfo * outAxisInfo) const1026 status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
1027     std::scoped_lock _l(mLock);
1028     Device* device = getDeviceLocked(deviceId);
1029 
1030     if (device != nullptr && device->keyMap.haveKeyLayout()) {
1031         status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
1032         if (err == NO_ERROR) {
1033             return NO_ERROR;
1034         }
1035     }
1036 
1037     return NAME_NOT_FOUND;
1038 }
1039 
mapSensor(int32_t deviceId,int32_t absCode)1040 base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
1041                                                                             int32_t absCode) {
1042     std::scoped_lock _l(mLock);
1043     Device* device = getDeviceLocked(deviceId);
1044 
1045     if (device != nullptr && device->keyMap.haveKeyLayout()) {
1046         return device->keyMap.keyLayoutMap->mapSensor(absCode);
1047     }
1048     return Errorf("Device not found or device has no key layout.");
1049 }
1050 
1051 // Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1052 // associated with the device ID. Returns an empty map if no miscellaneous device found.
getBatteryInfoLocked(int32_t deviceId) const1053 const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1054         int32_t deviceId) const {
1055     static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1056     Device* device = getDeviceLocked(deviceId);
1057     if (device == nullptr || !device->associatedDevice) {
1058         return EMPTY_BATTERY_INFO;
1059     }
1060     return device->associatedDevice->batteryInfos;
1061 }
1062 
getRawBatteryIds(int32_t deviceId)1063 const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
1064     std::scoped_lock _l(mLock);
1065     std::vector<int32_t> batteryIds;
1066 
1067     for (const auto [id, info] : getBatteryInfoLocked(deviceId)) {
1068         batteryIds.push_back(id);
1069     }
1070 
1071     return batteryIds;
1072 }
1073 
getRawBatteryInfo(int32_t deviceId,int32_t batteryId)1074 std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1075     std::scoped_lock _l(mLock);
1076 
1077     const auto infos = getBatteryInfoLocked(deviceId);
1078 
1079     auto it = infos.find(batteryId);
1080     if (it != infos.end()) {
1081         return it->second;
1082     }
1083 
1084     return std::nullopt;
1085 }
1086 
1087 // Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1088 // with the deivice ID. Returns an empty map if no miscellaneous device found.
getLightInfoLocked(int32_t deviceId) const1089 const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1090         int32_t deviceId) const {
1091     static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1092     Device* device = getDeviceLocked(deviceId);
1093     if (device == nullptr || !device->associatedDevice) {
1094         return EMPTY_LIGHT_INFO;
1095     }
1096     return device->associatedDevice->lightInfos;
1097 }
1098 
getRawLightIds(int32_t deviceId)1099 const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1100     std::scoped_lock _l(mLock);
1101     std::vector<int32_t> lightIds;
1102 
1103     for (const auto [id, info] : getLightInfoLocked(deviceId)) {
1104         lightIds.push_back(id);
1105     }
1106 
1107     return lightIds;
1108 }
1109 
getRawLightInfo(int32_t deviceId,int32_t lightId)1110 std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1111     std::scoped_lock _l(mLock);
1112 
1113     const auto infos = getLightInfoLocked(deviceId);
1114 
1115     auto it = infos.find(lightId);
1116     if (it != infos.end()) {
1117         return it->second;
1118     }
1119 
1120     return std::nullopt;
1121 }
1122 
getLightBrightness(int32_t deviceId,int32_t lightId)1123 std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1124     std::scoped_lock _l(mLock);
1125 
1126     const auto infos = getLightInfoLocked(deviceId);
1127     auto it = infos.find(lightId);
1128     if (it == infos.end()) {
1129         return std::nullopt;
1130     }
1131     std::string buffer;
1132     if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1133                                 &buffer)) {
1134         return std::nullopt;
1135     }
1136     return std::stoi(buffer);
1137 }
1138 
getLightIntensities(int32_t deviceId,int32_t lightId)1139 std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1140         int32_t deviceId, int32_t lightId) {
1141     std::scoped_lock _l(mLock);
1142 
1143     const auto infos = getLightInfoLocked(deviceId);
1144     auto lightIt = infos.find(lightId);
1145     if (lightIt == infos.end()) {
1146         return std::nullopt;
1147     }
1148 
1149     auto ret =
1150             getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1151 
1152     if (!ret.has_value()) {
1153         return std::nullopt;
1154     }
1155     std::array<LightColor, COLOR_NUM> colors = ret.value();
1156 
1157     std::string intensityStr;
1158     if (!base::ReadFileToString(lightIt->second.path /
1159                                         LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1160                                 &intensityStr)) {
1161         return std::nullopt;
1162     }
1163 
1164     // Intensity node outputs 3 color values
1165     std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1166     std::smatch results;
1167 
1168     if (!std::regex_match(intensityStr, results, intensityPattern)) {
1169         return std::nullopt;
1170     }
1171     std::unordered_map<LightColor, int32_t> intensities;
1172     for (size_t i = 1; i < results.size(); i++) {
1173         int value = std::stoi(results[i].str());
1174         intensities.emplace(colors[i - 1], value);
1175     }
1176     return intensities;
1177 }
1178 
setLightBrightness(int32_t deviceId,int32_t lightId,int32_t brightness)1179 void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1180     std::scoped_lock _l(mLock);
1181 
1182     const auto infos = getLightInfoLocked(deviceId);
1183     auto lightIt = infos.find(lightId);
1184     if (lightIt == infos.end()) {
1185         ALOGE("%s lightId %d not found ", __func__, lightId);
1186         return;
1187     }
1188 
1189     if (!base::WriteStringToFile(std::to_string(brightness),
1190                                  lightIt->second.path /
1191                                          LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1192         ALOGE("Can not write to file, error: %s", strerror(errno));
1193     }
1194 }
1195 
setLightIntensities(int32_t deviceId,int32_t lightId,std::unordered_map<LightColor,int32_t> intensities)1196 void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1197                                    std::unordered_map<LightColor, int32_t> intensities) {
1198     std::scoped_lock _l(mLock);
1199 
1200     const auto infos = getLightInfoLocked(deviceId);
1201     auto lightIt = infos.find(lightId);
1202     if (lightIt == infos.end()) {
1203         ALOGE("Light Id %d does not exist.", lightId);
1204         return;
1205     }
1206 
1207     auto ret =
1208             getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1209 
1210     if (!ret.has_value()) {
1211         return;
1212     }
1213     std::array<LightColor, COLOR_NUM> colors = ret.value();
1214 
1215     std::string rgbStr;
1216     for (size_t i = 0; i < COLOR_NUM; i++) {
1217         auto it = intensities.find(colors[i]);
1218         if (it != intensities.end()) {
1219             rgbStr += std::to_string(it->second);
1220             // Insert space between colors
1221             if (i < COLOR_NUM - 1) {
1222                 rgbStr += " ";
1223             }
1224         }
1225     }
1226     // Append new line
1227     rgbStr += "\n";
1228 
1229     if (!base::WriteStringToFile(rgbStr,
1230                                  lightIt->second.path /
1231                                          LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1232         ALOGE("Can not write to file, error: %s", strerror(errno));
1233     }
1234 }
1235 
setExcludedDevices(const std::vector<std::string> & devices)1236 void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
1237     std::scoped_lock _l(mLock);
1238 
1239     mExcludedDevices = devices;
1240 }
1241 
hasScanCode(int32_t deviceId,int32_t scanCode) const1242 bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
1243     std::scoped_lock _l(mLock);
1244     Device* device = getDeviceLocked(deviceId);
1245     if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1246         return device->keyBitmask.test(scanCode);
1247     }
1248     return false;
1249 }
1250 
hasKeyCode(int32_t deviceId,int32_t keyCode) const1251 bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1252     std::scoped_lock _l(mLock);
1253     Device* device = getDeviceLocked(deviceId);
1254     if (device != nullptr) {
1255         return device->hasKeycodeLocked(keyCode);
1256     }
1257     return false;
1258 }
1259 
hasLed(int32_t deviceId,int32_t led) const1260 bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
1261     std::scoped_lock _l(mLock);
1262     Device* device = getDeviceLocked(deviceId);
1263     int32_t sc;
1264     if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
1265         return device->ledBitmask.test(sc);
1266     }
1267     return false;
1268 }
1269 
setLedState(int32_t deviceId,int32_t led,bool on)1270 void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
1271     std::scoped_lock _l(mLock);
1272     Device* device = getDeviceLocked(deviceId);
1273     if (device != nullptr && device->hasValidFd()) {
1274         device->setLedStateLocked(led, on);
1275     }
1276 }
1277 
getVirtualKeyDefinitions(int32_t deviceId,std::vector<VirtualKeyDefinition> & outVirtualKeys) const1278 void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
1279                                         std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
1280     outVirtualKeys.clear();
1281 
1282     std::scoped_lock _l(mLock);
1283     Device* device = getDeviceLocked(deviceId);
1284     if (device != nullptr && device->virtualKeyMap) {
1285         const std::vector<VirtualKeyDefinition> virtualKeys =
1286                 device->virtualKeyMap->getVirtualKeys();
1287         outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
1288     }
1289 }
1290 
getKeyCharacterMap(int32_t deviceId) const1291 const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
1292     std::scoped_lock _l(mLock);
1293     Device* device = getDeviceLocked(deviceId);
1294     if (device != nullptr) {
1295         return device->getKeyCharacterMap();
1296     }
1297     return nullptr;
1298 }
1299 
setKeyboardLayoutOverlay(int32_t deviceId,std::shared_ptr<KeyCharacterMap> map)1300 bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
1301     std::scoped_lock _l(mLock);
1302     Device* device = getDeviceLocked(deviceId);
1303     if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1304         return false;
1305     }
1306     device->keyMap.keyCharacterMap->combine(*map);
1307     return true;
1308 }
1309 
generateDescriptor(InputDeviceIdentifier & identifier)1310 static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1311     std::string rawDescriptor;
1312     rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
1313     // TODO add handling for USB devices to not uniqueify kbs that show up twice
1314     if (!identifier.uniqueId.empty()) {
1315         rawDescriptor += "uniqueId:";
1316         rawDescriptor += identifier.uniqueId;
1317     } else if (identifier.nonce != 0) {
1318         rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
1319     }
1320 
1321     if (identifier.vendor == 0 && identifier.product == 0) {
1322         // If we don't know the vendor and product id, then the device is probably
1323         // built-in so we need to rely on other information to uniquely identify
1324         // the input device.  Usually we try to avoid relying on the device name or
1325         // location but for built-in input device, they are unlikely to ever change.
1326         if (!identifier.name.empty()) {
1327             rawDescriptor += "name:";
1328             rawDescriptor += identifier.name;
1329         } else if (!identifier.location.empty()) {
1330             rawDescriptor += "location:";
1331             rawDescriptor += identifier.location;
1332         }
1333     }
1334     identifier.descriptor = sha1(rawDescriptor);
1335     return rawDescriptor;
1336 }
1337 
assignDescriptorLocked(InputDeviceIdentifier & identifier)1338 void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1339     // Compute a device descriptor that uniquely identifies the device.
1340     // The descriptor is assumed to be a stable identifier.  Its value should not
1341     // change between reboots, reconnections, firmware updates or new releases
1342     // of Android. In practice we sometimes get devices that cannot be uniquely
1343     // identified. In this case we enforce uniqueness between connected devices.
1344     // Ideally, we also want the descriptor to be short and relatively opaque.
1345 
1346     identifier.nonce = 0;
1347     std::string rawDescriptor = generateDescriptor(identifier);
1348     if (identifier.uniqueId.empty()) {
1349         // If it didn't have a unique id check for conflicts and enforce
1350         // uniqueness if necessary.
1351         while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
1352             identifier.nonce++;
1353             rawDescriptor = generateDescriptor(identifier);
1354         }
1355     }
1356     ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
1357           identifier.descriptor.c_str());
1358 }
1359 
vibrate(int32_t deviceId,const VibrationElement & element)1360 void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
1361     std::scoped_lock _l(mLock);
1362     Device* device = getDeviceLocked(deviceId);
1363     if (device != nullptr && device->hasValidFd()) {
1364         ff_effect effect;
1365         memset(&effect, 0, sizeof(effect));
1366         effect.type = FF_RUMBLE;
1367         effect.id = device->ffEffectId;
1368         // evdev FF_RUMBLE effect only supports two channels of vibration.
1369         effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1370         effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1371         effect.replay.length = element.duration.count();
1372         effect.replay.delay = 0;
1373         if (ioctl(device->fd, EVIOCSFF, &effect)) {
1374             ALOGW("Could not upload force feedback effect to device %s due to error %d.",
1375                   device->identifier.name.c_str(), errno);
1376             return;
1377         }
1378         device->ffEffectId = effect.id;
1379 
1380         struct input_event ev;
1381         ev.time.tv_sec = 0;
1382         ev.time.tv_usec = 0;
1383         ev.type = EV_FF;
1384         ev.code = device->ffEffectId;
1385         ev.value = 1;
1386         if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1387             ALOGW("Could not start force feedback effect on device %s due to error %d.",
1388                   device->identifier.name.c_str(), errno);
1389             return;
1390         }
1391         device->ffEffectPlaying = true;
1392     }
1393 }
1394 
cancelVibrate(int32_t deviceId)1395 void EventHub::cancelVibrate(int32_t deviceId) {
1396     std::scoped_lock _l(mLock);
1397     Device* device = getDeviceLocked(deviceId);
1398     if (device != nullptr && device->hasValidFd()) {
1399         if (device->ffEffectPlaying) {
1400             device->ffEffectPlaying = false;
1401 
1402             struct input_event ev;
1403             ev.time.tv_sec = 0;
1404             ev.time.tv_usec = 0;
1405             ev.type = EV_FF;
1406             ev.code = device->ffEffectId;
1407             ev.value = 0;
1408             if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1409                 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
1410                       device->identifier.name.c_str(), errno);
1411                 return;
1412             }
1413         }
1414     }
1415 }
1416 
getVibratorIds(int32_t deviceId)1417 std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1418     std::scoped_lock _l(mLock);
1419     std::vector<int32_t> vibrators;
1420     Device* device = getDeviceLocked(deviceId);
1421     if (device != nullptr && device->hasValidFd() &&
1422         device->classes.test(InputDeviceClass::VIBRATOR)) {
1423         vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1424         vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1425     }
1426     return vibrators;
1427 }
1428 
getDeviceByDescriptorLocked(const std::string & descriptor) const1429 EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
1430     for (const auto& [id, device] : mDevices) {
1431         if (descriptor == device->identifier.descriptor) {
1432             return device.get();
1433         }
1434     }
1435     return nullptr;
1436 }
1437 
getDeviceLocked(int32_t deviceId) const1438 EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
1439     if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
1440         deviceId = mBuiltInKeyboardId;
1441     }
1442     const auto& it = mDevices.find(deviceId);
1443     return it != mDevices.end() ? it->second.get() : nullptr;
1444 }
1445 
getDeviceByPathLocked(const std::string & devicePath) const1446 EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
1447     for (const auto& [id, device] : mDevices) {
1448         if (device->path == devicePath) {
1449             return device.get();
1450         }
1451     }
1452     return nullptr;
1453 }
1454 
1455 /**
1456  * The file descriptor could be either input device, or a video device (associated with a
1457  * specific input device). Check both cases here, and return the device that this event
1458  * belongs to. Caller can compare the fd's once more to determine event type.
1459  * Looks through all input devices, and only attached video devices. Unattached video
1460  * devices are ignored.
1461  */
getDeviceByFdLocked(int fd) const1462 EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
1463     for (const auto& [id, device] : mDevices) {
1464         if (device->fd == fd) {
1465             // This is an input device event
1466             return device.get();
1467         }
1468         if (device->videoDevice && device->videoDevice->getFd() == fd) {
1469             // This is a video device event
1470             return device.get();
1471         }
1472     }
1473     // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1474     // and therefore should never be looked up by fd.
1475     return nullptr;
1476 }
1477 
getBatteryCapacity(int32_t deviceId,int32_t batteryId) const1478 std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
1479     std::scoped_lock _l(mLock);
1480 
1481     const auto infos = getBatteryInfoLocked(deviceId);
1482     auto it = infos.find(batteryId);
1483     if (it == infos.end()) {
1484         return std::nullopt;
1485     }
1486     std::string buffer;
1487 
1488     // Some devices report battery capacity as an integer through the "capacity" file
1489     if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1490                                &buffer)) {
1491         return std::stoi(base::Trim(buffer));
1492     }
1493 
1494     // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1495     // These values are taken from kernel source code include/linux/power_supply.h
1496     if (base::ReadFileToString(it->second.path /
1497                                        BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1498                                &buffer)) {
1499         // Remove any white space such as trailing new line
1500         const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1501         if (levelIt != BATTERY_LEVEL.end()) {
1502             return levelIt->second;
1503         }
1504     }
1505 
1506     return std::nullopt;
1507 }
1508 
getBatteryStatus(int32_t deviceId,int32_t batteryId) const1509 std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
1510     std::scoped_lock _l(mLock);
1511     const auto infos = getBatteryInfoLocked(deviceId);
1512     auto it = infos.find(batteryId);
1513     if (it == infos.end()) {
1514         return std::nullopt;
1515     }
1516     std::string buffer;
1517 
1518     if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1519                                 &buffer)) {
1520         ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1521         return std::nullopt;
1522     }
1523 
1524     // Remove white space like trailing new line
1525     const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1526     if (statusIt != BATTERY_STATUS.end()) {
1527         return statusIt->second;
1528     }
1529 
1530     return std::nullopt;
1531 }
1532 
getEvents(int timeoutMillis,RawEvent * buffer,size_t bufferSize)1533 size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1534     ALOG_ASSERT(bufferSize >= 1);
1535 
1536     std::scoped_lock _l(mLock);
1537 
1538     struct input_event readBuffer[bufferSize];
1539 
1540     RawEvent* event = buffer;
1541     size_t capacity = bufferSize;
1542     bool awoken = false;
1543     for (;;) {
1544         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1545 
1546         // Reopen input devices if needed.
1547         if (mNeedToReopenDevices) {
1548             mNeedToReopenDevices = false;
1549 
1550             ALOGI("Reopening all input devices due to a configuration change.");
1551 
1552             closeAllDevicesLocked();
1553             mNeedToScanDevices = true;
1554             break; // return to the caller before we actually rescan
1555         }
1556 
1557         // Report any devices that had last been added/removed.
1558         for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1559             std::unique_ptr<Device> device = std::move(*it);
1560             ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
1561             event->when = now;
1562             event->deviceId = (device->id == mBuiltInKeyboardId)
1563                     ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1564                     : device->id;
1565             event->type = DEVICE_REMOVED;
1566             event += 1;
1567             it = mClosingDevices.erase(it);
1568             mNeedToSendFinishedDeviceScan = true;
1569             if (--capacity == 0) {
1570                 break;
1571             }
1572         }
1573 
1574         if (mNeedToScanDevices) {
1575             mNeedToScanDevices = false;
1576             scanDevicesLocked();
1577             mNeedToSendFinishedDeviceScan = true;
1578         }
1579 
1580         while (!mOpeningDevices.empty()) {
1581             std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1582             mOpeningDevices.pop_back();
1583             ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
1584             event->when = now;
1585             event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1586             event->type = DEVICE_ADDED;
1587             event += 1;
1588 
1589             // Try to find a matching video device by comparing device names
1590             for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1591                  it++) {
1592                 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
1593                 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
1594                     // videoDevice was transferred to 'device'
1595                     it = mUnattachedVideoDevices.erase(it);
1596                     break;
1597                 }
1598             }
1599 
1600             auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1601             if (!inserted) {
1602                 ALOGW("Device id %d exists, replaced.", device->id);
1603             }
1604             mNeedToSendFinishedDeviceScan = true;
1605             if (--capacity == 0) {
1606                 break;
1607             }
1608         }
1609 
1610         if (mNeedToSendFinishedDeviceScan) {
1611             mNeedToSendFinishedDeviceScan = false;
1612             event->when = now;
1613             event->type = FINISHED_DEVICE_SCAN;
1614             event += 1;
1615             if (--capacity == 0) {
1616                 break;
1617             }
1618         }
1619 
1620         // Grab the next input event.
1621         bool deviceChanged = false;
1622         while (mPendingEventIndex < mPendingEventCount) {
1623             const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
1624             if (eventItem.data.fd == mINotifyFd) {
1625                 if (eventItem.events & EPOLLIN) {
1626                     mPendingINotify = true;
1627                 } else {
1628                     ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1629                 }
1630                 continue;
1631             }
1632 
1633             if (eventItem.data.fd == mWakeReadPipeFd) {
1634                 if (eventItem.events & EPOLLIN) {
1635                     ALOGV("awoken after wake()");
1636                     awoken = true;
1637                     char wakeReadBuffer[16];
1638                     ssize_t nRead;
1639                     do {
1640                         nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1641                     } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
1642                 } else {
1643                     ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
1644                           eventItem.events);
1645                 }
1646                 continue;
1647             }
1648 
1649             Device* device = getDeviceByFdLocked(eventItem.data.fd);
1650             if (device == nullptr) {
1651                 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1652                       eventItem.data.fd);
1653                 ALOG_ASSERT(!DEBUG);
1654                 continue;
1655             }
1656             if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1657                 if (eventItem.events & EPOLLIN) {
1658                     size_t numFrames = device->videoDevice->readAndQueueFrames();
1659                     if (numFrames == 0) {
1660                         ALOGE("Received epoll event for video device %s, but could not read frame",
1661                               device->videoDevice->getName().c_str());
1662                     }
1663                 } else if (eventItem.events & EPOLLHUP) {
1664                     // TODO(b/121395353) - consider adding EPOLLRDHUP
1665                     ALOGI("Removing video device %s due to epoll hang-up event.",
1666                           device->videoDevice->getName().c_str());
1667                     unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1668                     device->videoDevice = nullptr;
1669                 } else {
1670                     ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1671                           device->videoDevice->getName().c_str());
1672                     ALOG_ASSERT(!DEBUG);
1673                 }
1674                 continue;
1675             }
1676             // This must be an input event
1677             if (eventItem.events & EPOLLIN) {
1678                 int32_t readSize =
1679                         read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
1680                 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1681                     // Device was removed before INotify noticed.
1682                     ALOGW("could not get event, removed? (fd: %d size: %" PRId32
1683                           " bufferSize: %zu capacity: %zu errno: %d)\n",
1684                           device->fd, readSize, bufferSize, capacity, errno);
1685                     deviceChanged = true;
1686                     closeDeviceLocked(*device);
1687                 } else if (readSize < 0) {
1688                     if (errno != EAGAIN && errno != EINTR) {
1689                         ALOGW("could not get event (errno=%d)", errno);
1690                     }
1691                 } else if ((readSize % sizeof(struct input_event)) != 0) {
1692                     ALOGE("could not get event (wrong size: %d)", readSize);
1693                 } else {
1694                     int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1695 
1696                     size_t count = size_t(readSize) / sizeof(struct input_event);
1697                     for (size_t i = 0; i < count; i++) {
1698                         struct input_event& iev = readBuffer[i];
1699                         event->when = processEventTimestamp(iev);
1700                         event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
1701                         event->deviceId = deviceId;
1702                         event->type = iev.type;
1703                         event->code = iev.code;
1704                         event->value = iev.value;
1705                         event += 1;
1706                         capacity -= 1;
1707                     }
1708                     if (capacity == 0) {
1709                         // The result buffer is full.  Reset the pending event index
1710                         // so we will try to read the device again on the next iteration.
1711                         mPendingEventIndex -= 1;
1712                         break;
1713                     }
1714                 }
1715             } else if (eventItem.events & EPOLLHUP) {
1716                 ALOGI("Removing device %s due to epoll hang-up event.",
1717                       device->identifier.name.c_str());
1718                 deviceChanged = true;
1719                 closeDeviceLocked(*device);
1720             } else {
1721                 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1722                       device->identifier.name.c_str());
1723             }
1724         }
1725 
1726         // readNotify() will modify the list of devices so this must be done after
1727         // processing all other events to ensure that we read all remaining events
1728         // before closing the devices.
1729         if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1730             mPendingINotify = false;
1731             readNotifyLocked();
1732             deviceChanged = true;
1733         }
1734 
1735         // Report added or removed devices immediately.
1736         if (deviceChanged) {
1737             continue;
1738         }
1739 
1740         // Return now if we have collected any events or if we were explicitly awoken.
1741         if (event != buffer || awoken) {
1742             break;
1743         }
1744 
1745         // Poll for events.
1746         // When a device driver has pending (unread) events, it acquires
1747         // a kernel wake lock.  Once the last pending event has been read, the device
1748         // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1749         // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1750         // is called again for the same fd that produced the event.
1751         // Thus the system can only sleep if there are no events pending or
1752         // currently being processed.
1753         //
1754         // The timeout is advisory only.  If the device is asleep, it will not wake just to
1755         // service the timeout.
1756         mPendingEventIndex = 0;
1757 
1758         mLock.unlock(); // release lock before poll
1759 
1760         int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1761 
1762         mLock.lock(); // reacquire lock after poll
1763 
1764         if (pollResult == 0) {
1765             // Timed out.
1766             mPendingEventCount = 0;
1767             break;
1768         }
1769 
1770         if (pollResult < 0) {
1771             // An error occurred.
1772             mPendingEventCount = 0;
1773 
1774             // Sleep after errors to avoid locking up the system.
1775             // Hopefully the error is transient.
1776             if (errno != EINTR) {
1777                 ALOGW("poll failed (errno=%d)\n", errno);
1778                 usleep(100000);
1779             }
1780         } else {
1781             // Some events occurred.
1782             mPendingEventCount = size_t(pollResult);
1783         }
1784     }
1785 
1786     // All done, return the number of events we read.
1787     return event - buffer;
1788 }
1789 
getVideoFrames(int32_t deviceId)1790 std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1791     std::scoped_lock _l(mLock);
1792 
1793     Device* device = getDeviceLocked(deviceId);
1794     if (device == nullptr || !device->videoDevice) {
1795         return {};
1796     }
1797     return device->videoDevice->consumeFrames();
1798 }
1799 
wake()1800 void EventHub::wake() {
1801     ALOGV("wake() called");
1802 
1803     ssize_t nWrite;
1804     do {
1805         nWrite = write(mWakeWritePipeFd, "W", 1);
1806     } while (nWrite == -1 && errno == EINTR);
1807 
1808     if (nWrite != 1 && errno != EAGAIN) {
1809         ALOGW("Could not write wake signal: %s", strerror(errno));
1810     }
1811 }
1812 
scanDevicesLocked()1813 void EventHub::scanDevicesLocked() {
1814     status_t result;
1815     std::error_code errorCode;
1816 
1817     if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1818         result = scanDirLocked(DEVICE_INPUT_PATH);
1819         if (result < 0) {
1820             ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1821         }
1822     } else {
1823         if (errorCode) {
1824             ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1825                   errorCode.message().c_str());
1826         }
1827     }
1828     if (isV4lScanningEnabled()) {
1829         result = scanVideoDirLocked(DEVICE_PATH);
1830         if (result != OK) {
1831             ALOGE("scan video dir failed for %s", DEVICE_PATH);
1832         }
1833     }
1834     if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
1835         createVirtualKeyboardLocked();
1836     }
1837 }
1838 
1839 // ----------------------------------------------------------------------------
1840 
1841 static const int32_t GAMEPAD_KEYCODES[] = {
1842         AKEYCODE_BUTTON_A,      AKEYCODE_BUTTON_B,      AKEYCODE_BUTTON_C,    //
1843         AKEYCODE_BUTTON_X,      AKEYCODE_BUTTON_Y,      AKEYCODE_BUTTON_Z,    //
1844         AKEYCODE_BUTTON_L1,     AKEYCODE_BUTTON_R1,                           //
1845         AKEYCODE_BUTTON_L2,     AKEYCODE_BUTTON_R2,                           //
1846         AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,                       //
1847         AKEYCODE_BUTTON_START,  AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
1848 };
1849 
registerFdForEpoll(int fd)1850 status_t EventHub::registerFdForEpoll(int fd) {
1851     // TODO(b/121395353) - consider adding EPOLLRDHUP
1852     struct epoll_event eventItem = {};
1853     eventItem.events = EPOLLIN | EPOLLWAKEUP;
1854     eventItem.data.fd = fd;
1855     if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1856         ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
1857         return -errno;
1858     }
1859     return OK;
1860 }
1861 
unregisterFdFromEpoll(int fd)1862 status_t EventHub::unregisterFdFromEpoll(int fd) {
1863     if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1864         ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1865         return -errno;
1866     }
1867     return OK;
1868 }
1869 
registerDeviceForEpollLocked(Device & device)1870 status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1871     status_t result = registerFdForEpoll(device.fd);
1872     if (result != OK) {
1873         ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
1874         return result;
1875     }
1876     if (device.videoDevice) {
1877         registerVideoDeviceForEpollLocked(*device.videoDevice);
1878     }
1879     return result;
1880 }
1881 
registerVideoDeviceForEpollLocked(const TouchVideoDevice & videoDevice)1882 void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1883     status_t result = registerFdForEpoll(videoDevice.getFd());
1884     if (result != OK) {
1885         ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1886     }
1887 }
1888 
unregisterDeviceFromEpollLocked(Device & device)1889 status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1890     if (device.hasValidFd()) {
1891         status_t result = unregisterFdFromEpoll(device.fd);
1892         if (result != OK) {
1893             ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
1894             return result;
1895         }
1896     }
1897     if (device.videoDevice) {
1898         unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
1899     }
1900     return OK;
1901 }
1902 
unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice & videoDevice)1903 void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1904     if (videoDevice.hasValidFd()) {
1905         status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1906         if (result != OK) {
1907             ALOGW("Could not remove video device fd from epoll for device: %s",
1908                   videoDevice.getName().c_str());
1909         }
1910     }
1911 }
1912 
reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier & identifier,ftl::Flags<InputDeviceClass> classes)1913 void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
1914                                                     ftl::Flags<InputDeviceClass> classes) {
1915     SHA256_CTX ctx;
1916     SHA256_Init(&ctx);
1917     SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
1918                   identifier.uniqueId.size());
1919     std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
1920     SHA256_Final(digest.data(), &ctx);
1921 
1922     std::string obfuscatedId;
1923     for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
1924         obfuscatedId += StringPrintf("%02x", digest[i]);
1925     }
1926 
1927     android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1928                                identifier.vendor, identifier.product, identifier.version,
1929                                identifier.bus, obfuscatedId.c_str(), classes.get());
1930 }
1931 
openDeviceLocked(const std::string & devicePath)1932 void EventHub::openDeviceLocked(const std::string& devicePath) {
1933     // If an input device happens to register around the time when EventHub's constructor runs, it
1934     // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1935     // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1936     // from getting registered, ensure that this path is not already covered by an existing device.
1937     for (const auto& [deviceId, device] : mDevices) {
1938         if (device->path == devicePath) {
1939             return; // device was already registered
1940         }
1941     }
1942 
1943     char buffer[80];
1944 
1945     ALOGV("Opening device: %s", devicePath.c_str());
1946 
1947     int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
1948     if (fd < 0) {
1949         ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
1950         return;
1951     }
1952 
1953     InputDeviceIdentifier identifier;
1954 
1955     // Get device name.
1956     if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1957         ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
1958     } else {
1959         buffer[sizeof(buffer) - 1] = '\0';
1960         identifier.name = buffer;
1961     }
1962 
1963     // Check to see if the device is on our excluded list
1964     for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1965         const std::string& item = mExcludedDevices[i];
1966         if (identifier.name == item) {
1967             ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
1968             close(fd);
1969             return;
1970         }
1971     }
1972 
1973     // Get device driver version.
1974     int driverVersion;
1975     if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1976         ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
1977         close(fd);
1978         return;
1979     }
1980 
1981     // Get device identifier.
1982     struct input_id inputId;
1983     if (ioctl(fd, EVIOCGID, &inputId)) {
1984         ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
1985         close(fd);
1986         return;
1987     }
1988     identifier.bus = inputId.bustype;
1989     identifier.product = inputId.product;
1990     identifier.vendor = inputId.vendor;
1991     identifier.version = inputId.version;
1992 
1993     // Get device physical location.
1994     if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1995         // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1996     } else {
1997         buffer[sizeof(buffer) - 1] = '\0';
1998         identifier.location = buffer;
1999     }
2000 
2001     // Get device unique id.
2002     if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2003         // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
2004     } else {
2005         buffer[sizeof(buffer) - 1] = '\0';
2006         identifier.uniqueId = buffer;
2007     }
2008 
2009     // Fill in the descriptor.
2010     assignDescriptorLocked(identifier);
2011 
2012     // Allocate device.  (The device object takes ownership of the fd at this point.)
2013     int32_t deviceId = mNextDeviceId++;
2014     std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
2015 
2016     ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
2017     ALOGV("  bus:        %04x\n"
2018           "  vendor      %04x\n"
2019           "  product     %04x\n"
2020           "  version     %04x\n",
2021           identifier.bus, identifier.vendor, identifier.product, identifier.version);
2022     ALOGV("  name:       \"%s\"\n", identifier.name.c_str());
2023     ALOGV("  location:   \"%s\"\n", identifier.location.c_str());
2024     ALOGV("  unique id:  \"%s\"\n", identifier.uniqueId.c_str());
2025     ALOGV("  descriptor: \"%s\"\n", identifier.descriptor.c_str());
2026     ALOGV("  driver:     v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2027           driverVersion & 0xff);
2028 
2029     // Load the configuration file for the device.
2030     device->loadConfigurationLocked();
2031 
2032     bool hasBattery = false;
2033     bool hasLights = false;
2034     // Check the sysfs root path
2035     std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
2036     if (sysfsRootPath.has_value()) {
2037         std::shared_ptr<AssociatedDevice> associatedDevice;
2038         for (const auto& [id, dev] : mDevices) {
2039             if (device->identifier.descriptor == dev->identifier.descriptor &&
2040                 !dev->associatedDevice) {
2041                 associatedDevice = dev->associatedDevice;
2042             }
2043         }
2044         if (!associatedDevice) {
2045             associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
2046         }
2047         hasBattery = associatedDevice->configureBatteryLocked();
2048         hasLights = associatedDevice->configureLightsLocked();
2049 
2050         device->associatedDevice = associatedDevice;
2051     }
2052 
2053     // Figure out the kinds of events the device reports.
2054     device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2055     device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2056     device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2057     device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2058     device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2059     device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
2060     device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
2061     device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
2062 
2063     // See if this is a keyboard.  Ignore everything in the button range except for
2064     // joystick and gamepad buttons which are handled like keyboards for the most part.
2065     bool haveKeyboardKeys =
2066             device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2067     bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2068             device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
2069     if (haveKeyboardKeys || haveGamepadButtons) {
2070         device->classes |= InputDeviceClass::KEYBOARD;
2071     }
2072 
2073     // See if this is a cursor device such as a trackball or mouse.
2074     if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2075         device->relBitmask.test(REL_Y)) {
2076         device->classes |= InputDeviceClass::CURSOR;
2077     }
2078 
2079     // See if this is a rotary encoder type device.
2080     String8 deviceType = String8();
2081     if (device->configuration &&
2082         device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
2083         if (!deviceType.compare(String8("rotaryEncoder"))) {
2084             device->classes |= InputDeviceClass::ROTARY_ENCODER;
2085         }
2086     }
2087 
2088     // See if this is a touch pad.
2089     // Is this a new modern multi-touch driver?
2090     if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
2091         // Some joysticks such as the PS3 controller report axes that conflict
2092         // with the ABS_MT range.  Try to confirm that the device really is
2093         // a touch screen.
2094         if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
2095             device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
2096         }
2097         // Is this an old style single-touch driver?
2098     } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2099                device->absBitmask.test(ABS_Y)) {
2100         device->classes |= InputDeviceClass::TOUCH;
2101         // Is this a BT stylus?
2102     } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2103                !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
2104         device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2105         // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2106         // can fuse it with the touch screen data, so just take them back. Note this means an
2107         // external stylus cannot also be a keyboard device.
2108         device->classes &= ~InputDeviceClass::KEYBOARD;
2109     }
2110 
2111     // See if this device is a joystick.
2112     // Assumes that joysticks always have gamepad buttons in order to distinguish them
2113     // from other devices such as accelerometers that also have absolute axes.
2114     if (haveGamepadButtons) {
2115         auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
2116         for (int i = 0; i <= ABS_MAX; i++) {
2117             if (device->absBitmask.test(i) &&
2118                 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
2119                 device->classes = assumedClasses;
2120                 break;
2121             }
2122         }
2123     }
2124 
2125     // Check whether this device is an accelerometer.
2126     if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2127         device->classes |= InputDeviceClass::SENSOR;
2128     }
2129 
2130     // Check whether this device has switches.
2131     for (int i = 0; i <= SW_MAX; i++) {
2132         if (device->swBitmask.test(i)) {
2133             device->classes |= InputDeviceClass::SWITCH;
2134             break;
2135         }
2136     }
2137 
2138     // Check whether this device supports the vibrator.
2139     if (device->ffBitmask.test(FF_RUMBLE)) {
2140         device->classes |= InputDeviceClass::VIBRATOR;
2141     }
2142 
2143     // Configure virtual keys.
2144     if ((device->classes.test(InputDeviceClass::TOUCH))) {
2145         // Load the virtual keys for the touch screen, if any.
2146         // We do this now so that we can make sure to load the keymap if necessary.
2147         bool success = device->loadVirtualKeyMapLocked();
2148         if (success) {
2149             device->classes |= InputDeviceClass::KEYBOARD;
2150         }
2151     }
2152 
2153     // Load the key map.
2154     // We need to do this for joysticks too because the key layout may specify axes, and for
2155     // sensor as well because the key layout may specify the axes to sensor data mapping.
2156     status_t keyMapStatus = NAME_NOT_FOUND;
2157     if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2158                             InputDeviceClass::SENSOR)) {
2159         // Load the keymap for the device.
2160         keyMapStatus = device->loadKeyMapLocked();
2161     }
2162 
2163     // Configure the keyboard, gamepad or virtual keyboard.
2164     if (device->classes.test(InputDeviceClass::KEYBOARD)) {
2165         // Register the keyboard as a built-in keyboard if it is eligible.
2166         if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
2167             isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2168                                       &device->keyMap)) {
2169             mBuiltInKeyboardId = device->id;
2170         }
2171 
2172         // 'Q' key support = cheap test of whether this is an alpha-capable kbd
2173         if (device->hasKeycodeLocked(AKEYCODE_Q)) {
2174             device->classes |= InputDeviceClass::ALPHAKEY;
2175         }
2176 
2177         // See if this device has a DPAD.
2178         if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2179             device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2180             device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2181             device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2182             device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
2183             device->classes |= InputDeviceClass::DPAD;
2184         }
2185 
2186         // See if this device has a gamepad.
2187         for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
2188             if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
2189                 device->classes |= InputDeviceClass::GAMEPAD;
2190                 break;
2191             }
2192         }
2193     }
2194 
2195     // If the device isn't recognized as something we handle, don't monitor it.
2196     if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
2197         ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
2198               device->identifier.name.c_str());
2199         return;
2200     }
2201 
2202     // Classify InputDeviceClass::BATTERY.
2203     if (hasBattery) {
2204         device->classes |= InputDeviceClass::BATTERY;
2205     }
2206 
2207     // Classify InputDeviceClass::LIGHT.
2208     if (hasLights) {
2209         device->classes |= InputDeviceClass::LIGHT;
2210     }
2211 
2212     // Determine whether the device has a mic.
2213     if (device->deviceHasMicLocked()) {
2214         device->classes |= InputDeviceClass::MIC;
2215     }
2216 
2217     // Determine whether the device is external or internal.
2218     if (device->isExternalDeviceLocked()) {
2219         device->classes |= InputDeviceClass::EXTERNAL;
2220     }
2221 
2222     if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2223         device->classes.test(InputDeviceClass::GAMEPAD)) {
2224         device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2225         device->setLedForControllerLocked();
2226     }
2227 
2228     if (registerDeviceForEpollLocked(*device) != OK) {
2229         return;
2230     }
2231 
2232     device->configureFd();
2233 
2234     ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
2235           "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
2236           deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2237           device->classes.string().c_str(), device->configurationFile.c_str(),
2238           device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2239           toString(mBuiltInKeyboardId == deviceId));
2240 
2241     addDeviceLocked(std::move(device));
2242 }
2243 
openVideoDeviceLocked(const std::string & devicePath)2244 void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2245     std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2246     if (!videoDevice) {
2247         ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2248         return;
2249     }
2250     // Transfer ownership of this video device to a matching input device
2251     for (const auto& [id, device] : mDevices) {
2252         if (tryAddVideoDeviceLocked(*device, videoDevice)) {
2253             return; // 'device' now owns 'videoDevice'
2254         }
2255     }
2256 
2257     // Couldn't find a matching input device, so just add it to a temporary holding queue.
2258     // A matching input device may appear later.
2259     ALOGI("Adding video device %s to list of unattached video devices",
2260           videoDevice->getName().c_str());
2261     mUnattachedVideoDevices.push_back(std::move(videoDevice));
2262 }
2263 
tryAddVideoDeviceLocked(EventHub::Device & device,std::unique_ptr<TouchVideoDevice> & videoDevice)2264 bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2265                                        std::unique_ptr<TouchVideoDevice>& videoDevice) {
2266     if (videoDevice->getName() != device.identifier.name) {
2267         return false;
2268     }
2269     device.videoDevice = std::move(videoDevice);
2270     if (device.enabled) {
2271         registerVideoDeviceForEpollLocked(*device.videoDevice);
2272     }
2273     return true;
2274 }
2275 
isDeviceEnabled(int32_t deviceId)2276 bool EventHub::isDeviceEnabled(int32_t deviceId) {
2277     std::scoped_lock _l(mLock);
2278     Device* device = getDeviceLocked(deviceId);
2279     if (device == nullptr) {
2280         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2281         return false;
2282     }
2283     return device->enabled;
2284 }
2285 
enableDevice(int32_t deviceId)2286 status_t EventHub::enableDevice(int32_t deviceId) {
2287     std::scoped_lock _l(mLock);
2288     Device* device = getDeviceLocked(deviceId);
2289     if (device == nullptr) {
2290         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2291         return BAD_VALUE;
2292     }
2293     if (device->enabled) {
2294         ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2295         return OK;
2296     }
2297     status_t result = device->enable();
2298     if (result != OK) {
2299         ALOGE("Failed to enable device %" PRId32, deviceId);
2300         return result;
2301     }
2302 
2303     device->configureFd();
2304 
2305     return registerDeviceForEpollLocked(*device);
2306 }
2307 
disableDevice(int32_t deviceId)2308 status_t EventHub::disableDevice(int32_t deviceId) {
2309     std::scoped_lock _l(mLock);
2310     Device* device = getDeviceLocked(deviceId);
2311     if (device == nullptr) {
2312         ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2313         return BAD_VALUE;
2314     }
2315     if (!device->enabled) {
2316         ALOGW("Duplicate call to %s, input device already disabled", __func__);
2317         return OK;
2318     }
2319     unregisterDeviceFromEpollLocked(*device);
2320     return device->disable();
2321 }
2322 
createVirtualKeyboardLocked()2323 void EventHub::createVirtualKeyboardLocked() {
2324     InputDeviceIdentifier identifier;
2325     identifier.name = "Virtual";
2326     identifier.uniqueId = "<virtual>";
2327     assignDescriptorLocked(identifier);
2328 
2329     std::unique_ptr<Device> device =
2330             std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2331                                      identifier);
2332     device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2333             InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
2334     device->loadKeyMapLocked();
2335     addDeviceLocked(std::move(device));
2336 }
2337 
addDeviceLocked(std::unique_ptr<Device> device)2338 void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
2339     reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
2340     mOpeningDevices.push_back(std::move(device));
2341 }
2342 
getNextControllerNumberLocked(const std::string & name)2343 int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
2344     if (mControllerNumbers.isFull()) {
2345         ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
2346               name.c_str());
2347         return 0;
2348     }
2349     // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2350     // one
2351     return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2352 }
2353 
releaseControllerNumberLocked(int32_t num)2354 void EventHub::releaseControllerNumberLocked(int32_t num) {
2355     if (num > 0) {
2356         mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
2357     }
2358 }
2359 
closeDeviceByPathLocked(const std::string & devicePath)2360 void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
2361     Device* device = getDeviceByPathLocked(devicePath);
2362     if (device != nullptr) {
2363         closeDeviceLocked(*device);
2364         return;
2365     }
2366     ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
2367 }
2368 
2369 /**
2370  * Find the video device by filename, and close it.
2371  * The video device is closed by path during an inotify event, where we don't have the
2372  * additional context about the video device fd, or the associated input device.
2373  */
closeVideoDeviceByPathLocked(const std::string & devicePath)2374 void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
2375     // A video device may be owned by an existing input device, or it may be stored in
2376     // the mUnattachedVideoDevices queue. Check both locations.
2377     for (const auto& [id, device] : mDevices) {
2378         if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
2379             unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
2380             device->videoDevice = nullptr;
2381             return;
2382         }
2383     }
2384     std::erase_if(mUnattachedVideoDevices,
2385                   [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2386                       return videoDevice->getPath() == devicePath;
2387                   });
2388 }
2389 
closeAllDevicesLocked()2390 void EventHub::closeAllDevicesLocked() {
2391     mUnattachedVideoDevices.clear();
2392     while (!mDevices.empty()) {
2393         closeDeviceLocked(*(mDevices.begin()->second));
2394     }
2395 }
2396 
closeDeviceLocked(Device & device)2397 void EventHub::closeDeviceLocked(Device& device) {
2398     ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2399           device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
2400 
2401     if (device.id == mBuiltInKeyboardId) {
2402         ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
2403               device.path.c_str(), mBuiltInKeyboardId);
2404         mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2405     }
2406 
2407     unregisterDeviceFromEpollLocked(device);
2408     if (device.videoDevice) {
2409         // This must be done after the video device is removed from epoll
2410         mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
2411     }
2412 
2413     releaseControllerNumberLocked(device.controllerNumber);
2414     device.controllerNumber = 0;
2415     device.close();
2416     mClosingDevices.push_back(std::move(mDevices[device.id]));
2417 
2418     mDevices.erase(device.id);
2419 }
2420 
readNotifyLocked()2421 status_t EventHub::readNotifyLocked() {
2422     int res;
2423     char event_buf[512];
2424     int event_size;
2425     int event_pos = 0;
2426     struct inotify_event* event;
2427 
2428     ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2429     res = read(mINotifyFd, event_buf, sizeof(event_buf));
2430     if (res < (int)sizeof(*event)) {
2431         if (errno == EINTR) return 0;
2432         ALOGW("could not get event, %s\n", strerror(errno));
2433         return -1;
2434     }
2435 
2436     while (res >= (int)sizeof(*event)) {
2437         event = (struct inotify_event*)(event_buf + event_pos);
2438         if (event->len) {
2439             if (event->wd == mDeviceInputWd) {
2440                 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event->name;
2441                 if (event->mask & IN_CREATE) {
2442                     openDeviceLocked(filename);
2443                 } else {
2444                     ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2445                     closeDeviceByPathLocked(filename);
2446                 }
2447             } else if (event->wd == mDeviceWd) {
2448                 if (isV4lTouchNode(event->name)) {
2449                     std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
2450                     if (event->mask & IN_CREATE) {
2451                         openVideoDeviceLocked(filename);
2452                     } else {
2453                         ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2454                         closeVideoDeviceByPathLocked(filename);
2455                     }
2456                 } else if (strcmp(event->name, "input") == 0 && event->mask & IN_CREATE) {
2457                     addDeviceInputInotify();
2458                 }
2459             } else {
2460                 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
2461             }
2462         }
2463         event_size = sizeof(*event) + event->len;
2464         res -= event_size;
2465         event_pos += event_size;
2466     }
2467     return 0;
2468 }
2469 
scanDirLocked(const std::string & dirname)2470 status_t EventHub::scanDirLocked(const std::string& dirname) {
2471     for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2472         openDeviceLocked(entry.path());
2473     }
2474     return 0;
2475 }
2476 
2477 /**
2478  * Look for all dirname/v4l-touch* devices, and open them.
2479  */
scanVideoDirLocked(const std::string & dirname)2480 status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
2481     for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2482         if (isV4lTouchNode(entry.path())) {
2483             ALOGI("Found touch video device %s", entry.path().c_str());
2484             openVideoDeviceLocked(entry.path());
2485         }
2486     }
2487     return OK;
2488 }
2489 
requestReopenDevices()2490 void EventHub::requestReopenDevices() {
2491     ALOGV("requestReopenDevices() called");
2492 
2493     std::scoped_lock _l(mLock);
2494     mNeedToReopenDevices = true;
2495 }
2496 
dump(std::string & dump)2497 void EventHub::dump(std::string& dump) {
2498     dump += "Event Hub State:\n";
2499 
2500     { // acquire lock
2501         std::scoped_lock _l(mLock);
2502 
2503         dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
2504 
2505         dump += INDENT "Devices:\n";
2506 
2507         for (const auto& [id, device] : mDevices) {
2508             if (mBuiltInKeyboardId == device->id) {
2509                 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
2510                                      device->id, device->identifier.name.c_str());
2511             } else {
2512                 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
2513                                      device->identifier.name.c_str());
2514             }
2515             dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
2516             dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
2517             dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
2518             dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2519             dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
2520             dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
2521             dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
2522             dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
2523                                          "product=0x%04x, version=0x%04x\n",
2524                                  device->identifier.bus, device->identifier.vendor,
2525                                  device->identifier.product, device->identifier.version);
2526             dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
2527                                  device->keyMap.keyLayoutFile.c_str());
2528             dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
2529                                  device->keyMap.keyCharacterMapFile.c_str());
2530             dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
2531                                  device->configurationFile.c_str());
2532             dump += INDENT3 "VideoDevice: ";
2533             if (device->videoDevice) {
2534                 dump += device->videoDevice->dump() + "\n";
2535             } else {
2536                 dump += "<none>\n";
2537             }
2538         }
2539 
2540         dump += INDENT "Unattached video devices:\n";
2541         for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2542             dump += INDENT2 + videoDevice->dump() + "\n";
2543         }
2544         if (mUnattachedVideoDevices.empty()) {
2545             dump += INDENT2 "<none>\n";
2546         }
2547     } // release lock
2548 }
2549 
monitor()2550 void EventHub::monitor() {
2551     // Acquire and release the lock to ensure that the event hub has not deadlocked.
2552     std::unique_lock<std::mutex> lock(mLock);
2553 }
2554 
2555 }; // namespace android
2556