• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "input_device_manager.h"
17 #include <algorithm>
18 #include <cstdio>
19 #include <cstdlib>
20 #include <cstring>
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <fstream>
24 #include <functional>
25 #include <future>
26 #include <iostream>
27 #include <memory>
28 #include <sstream>
29 #include <sys/epoll.h>
30 #include <sys/inotify.h>
31 #include <sys/ioctl.h>
32 #include <unistd.h>
33 #include <vector>
34 #include "input_uhdf_log.h"
35 #include "osal_mem.h"
36 #include "securec.h"
37 
38 #define HDF_LOG_TAG InputDeviceHdiManager
39 #define DRIVERS_PERIPHERAL_INPUT_FDSAN_TAG 0xC02555
40 
41 namespace OHOS {
42 namespace Input {
43 using namespace std;
44 constexpr uint32_t DEV_INDEX_MAX = 32;
45 constexpr uint32_t RELOAD_INTERVAL_MAX = 800;
46 const int32_t INVALID_ID = -1;
47 const int32_t MEMCPY_ERROR = -1;
48 const int32_t CREATE_SUCCESS = 1;
49 const int32_t CREATE_ERROR = 0;
Init()50 void InputDeviceManager::Init()
51 {
52     inputDevList_.clear();
53     reportEventPkgCallBackLock_.lock();
54     reportEventPkgCallback_.clear();
55     reportEventPkgCallBackLock_.unlock();
56     std::vector<std::string> flist = GetFiles(devPath_);
57     LoadInputDevices(flist);
58     std::thread reloadThread(&InputDeviceManager::ReloadInputDevices, this, flist);
59     reloadThread.detach();
60     std::thread t1([this] {this->WorkerThread();});
61     std::string wholeName1 = std::to_string(getpid()) + "_" + std::to_string(gettid());
62     thread_ = std::move(t1);
63     thread_.detach();
64     for (auto &inputDev : inputDevList_) {
65         dumpInfoList(inputDev.second);
66     }
67 }
68 
FreeEventPkgs(InputEventPackage ** eventPkgs,size_t count)69 static void FreeEventPkgs(InputEventPackage **eventPkgs, size_t count)
70 {
71     for (size_t i = 0; i < count; i++) {
72         if (eventPkgs[i] != NULL) {
73             OsalMemFree(eventPkgs[i]);
74             eventPkgs[i] = nullptr;
75         }
76     }
77     return;
78 }
79 
80 // get the nodefile list
GetFiles(string path)81 vector<string> InputDeviceManager::GetFiles(string path)
82 {
83     vector<string> fileList;
84     struct dirent *dEnt = nullptr;
85 
86     DIR *dir = opendir(path.c_str());
87     if (dir == nullptr) {
88         HDF_LOGE("%{public}s: no files", __func__);
89         return fileList;
90     }
91     string sDot = ".";
92     string sDotDot = "..";
93     while ((dEnt = readdir(dir)) != nullptr) {
94         if ((string(dEnt->d_name) != sDot) &&
95             (string(dEnt->d_name) != sDotDot)) {
96             if (dEnt->d_type != DT_DIR) {
97                 string d_name(dEnt->d_name);
98                 fileList.push_back(string(dEnt->d_name));
99             }
100         }
101     }
102     // sort the returned files
103     sort(fileList.begin(), fileList.end());
104     closedir(dir);
105     return fileList;
106 }
107 
ReportEventPkg(int32_t iFd,InputEventPackage ** iEvtPkg,size_t iCount)108 void InputDeviceManager::ReportEventPkg(int32_t iFd, InputEventPackage **iEvtPkg, size_t iCount)
109 {
110     HDF_LOGI("%{public}s start", __func__);
111     if (iEvtPkg == nullptr) {
112         HDF_LOGE("%{public}s: param invalid, line: %{public}d", __func__, __LINE__);
113         return;
114     }
115     std::lock_guard<std::mutex> guard(reportEventPkgCallBackLock_);
116     for (auto &callbackFunc : reportEventPkgCallback_) {
117         uint32_t index {0};
118         auto ret = FindIndexFromFd(iFd, &index);
119         if (callbackFunc.second != nullptr && ret != INPUT_FAILURE) {
120             callbackFunc.second->EventPkgCallback(const_cast<const InputEventPackage **>(iEvtPkg), iCount, index);
121         }
122     }
123     return;
124 }
125 
CheckReadResult(int32_t readResult)126 int32_t CheckReadResult(int32_t readResult)
127 {
128     if (readResult == 0 || (readResult < 0 && errno == ENODEV)) {
129         return INPUT_FAILURE;
130     }
131     if (readResult < 0) {
132         if (errno != EAGAIN && errno != EINTR) {
133             HDF_LOGE("%{public}s: could not get event (errno = %{public}d)", __func__, errno);
134         }
135         return INPUT_FAILURE;
136     }
137     if ((readResult % sizeof(struct input_event)) != 0) {
138         HDF_LOGE("%{public}s: could not get one event size %{public}lu readResult size: %{public}d", __func__,
139             sizeof(struct input_event), readResult);
140         return INPUT_FAILURE;
141     }
142     return INPUT_SUCCESS;
143 }
144 
145 // read action
DoRead(int32_t fd,struct input_event * event,size_t size)146 void InputDeviceManager::DoRead(int32_t fd, struct input_event *event, size_t size)
147 {
148     HDF_LOGI("%{public}s start", __func__);
149     int32_t readLen = read(fd, event, sizeof(struct input_event) * size);
150     if (CheckReadResult(readLen) == INPUT_FAILURE) {
151         return;
152     }
153     size_t count = size_t(readLen) / sizeof(struct input_event);
154     InputEventPackage **evtPkg = (InputEventPackage **)OsalMemAlloc(sizeof(InputEventPackage *) * count);
155     if (evtPkg == nullptr) {
156         HDF_LOGE("%{public}s: OsalMemAlloc failed, line: %{public}d", __func__, __LINE__);
157         return;
158     }
159     for (size_t i = 0; i < count; i++) {
160         struct input_event &iEvent = event[i];
161         // device action events happened
162         *(evtPkg + i) = (InputEventPackage *)OsalMemAlloc(sizeof(InputEventPackage));
163         if (evtPkg[i] == nullptr) {
164             HDF_LOGE("%{public}s: OsalMemAlloc failed, line: %{public}d", __func__, __LINE__);
165             FreeEventPkgs(evtPkg, i);
166             OsalMemFree(evtPkg);
167             evtPkg = nullptr;
168             return;
169         }
170         evtPkg[i]->type = iEvent.type;
171         evtPkg[i]->code = iEvent.code;
172         evtPkg[i]->value = iEvent.value;
173         evtPkg[i]->timestamp = (uint64_t)iEvent.time.tv_sec * MS_THOUSAND * MS_THOUSAND +
174                                (uint64_t)iEvent.time.tv_usec;
175     }
176     ReportEventPkg(fd, evtPkg, count);
177     for (size_t i = 0; i < count; i++) {
178         OsalMemFree(evtPkg[i]);
179         evtPkg[i] = nullptr;
180     }
181     OsalMemFree(evtPkg);
182     evtPkg = nullptr;
183 }
184 
185 // open input device node
OpenInputDevice(string devPath)186 int32_t InputDeviceManager::OpenInputDevice(string devPath)
187 {
188     char devRealPath[PATH_MAX + 1] = { '\0' };
189     if (realpath(devPath.c_str(), devRealPath) == nullptr) {
190         HDF_LOGE("%{public}s: The absolute path does not exist.", __func__);
191         return INPUT_FAILURE;
192     }
193 
194     int32_t nodeFd = open(devRealPath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
195     if (nodeFd < 0) {
196         HDF_LOGE("%{public}s: could not open %{public}s, %{public}d %{public}s", __func__,
197             devRealPath, errno, strerror(errno));
198         return INPUT_FAILURE;
199     }
200     uint64_t ownerTag = fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DRIVERS_PERIPHERAL_INPUT_FDSAN_TAG);
201     fdsan_exchange_owner_tag(nodeFd, 0, ownerTag);
202     return nodeFd;
203 }
204 
205 // close input device node
CloseInputDevice(string devPath)206 RetStatus InputDeviceManager::CloseInputDevice(string devPath)
207 {
208     auto it = std::find_if(inputDevList_.begin(), inputDevList_.end(), [&devPath](const auto &inputDev) {
209             return string(inputDev.second.devPathNode) == devPath;
210         });
211     if (it == inputDevList_.end()) {
212         return INPUT_FAILURE;
213     }
214     int32_t fd = it->second.fd;
215     if (fd <= 0) {
216         return INPUT_FAILURE;
217     }
218 
219     RemoveEpoll(mEpollId_, fd);
220     uint64_t ownerTag = fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DRIVERS_PERIPHERAL_INPUT_FDSAN_TAG);
221     fdsan_close_with_tag(fd, ownerTag);
222 
223     it->second.fd = -1;
224     it->second.status = INPUT_DEVICE_STATUS_CLOSED;
225     return INPUT_SUCCESS;
226 }
227 
GetInputDeviceInfo(int32_t fd,InputDeviceInfo * detailInfo)228 int32_t InputDeviceManager::GetInputDeviceInfo(int32_t fd, InputDeviceInfo *detailInfo)
229 {
230     char buffer[DEVICE_INFO_SIZE] {};
231     struct input_id inputId {};
232     // get the abilitys.
233     (void)ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(detailInfo->abilitySet.keyCode)), &detailInfo->abilitySet.keyCode);
234     (void)ioctl(fd, EVIOCGBIT(EV_REL, sizeof(detailInfo->abilitySet.relCode)), &detailInfo->abilitySet.relCode);
235     (void)ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(detailInfo->abilitySet.absCode)), &detailInfo->abilitySet.absCode);
236     (void)ioctl(fd, EVIOCGBIT(EV_MSC, sizeof(detailInfo->abilitySet.miscCode)), &detailInfo->abilitySet.miscCode);
237     (void)ioctl(fd, EVIOCGBIT(EV_SW, sizeof(detailInfo->abilitySet.switchCode)), &detailInfo->abilitySet.switchCode);
238     (void)ioctl(fd, EVIOCGBIT(EV_LED, sizeof(detailInfo->abilitySet.ledType)), &detailInfo->abilitySet.ledType);
239     (void)ioctl(fd, EVIOCGBIT(EV_SND, sizeof(detailInfo->abilitySet.soundCode)), &detailInfo->abilitySet.soundCode);
240     (void)ioctl(fd, EVIOCGBIT(EV_FF, sizeof(detailInfo->abilitySet.forceCode)), &detailInfo->abilitySet.forceCode);
241     // device name.
242     if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
243         HDF_LOGE("%{public}s: get device name failed errormsg %{public}s", __func__, strerror(errno));
244     } else {
245         buffer[sizeof(buffer) - 1] = '\0';
246         int32_t ret = strcpy_s(detailInfo->attrSet.devName, DEV_NAME_LEN, buffer);
247         if (ret) {
248             HDF_LOGE("%{public}s: strcpy_s failed, ret %{public}d", __func__, ret);
249             return INPUT_FAILURE;
250         }
251     }
252     // device detailInfo.
253     if (ioctl(fd, EVIOCGID, &inputId)) {
254         HDF_LOGE("%{public}s: get device input id errormsg %{public}s", __func__, strerror(errno));
255     }
256     detailInfo->attrSet.id.busType = inputId.bustype;
257     detailInfo->attrSet.id.product = inputId.product;
258     detailInfo->attrSet.id.vendor = inputId.vendor;
259     detailInfo->attrSet.id.version = inputId.version;
260     // ABS Info
261     for (uint32_t i = 0; i < BITS_TO_UINT64(ABS_CNT); i++) {
262         if (detailInfo->abilitySet.absCode[i] > 0) {
263             if (ioctl(fd, EVIOCGABS(i), &detailInfo->attrSet.axisInfo[i])) {
264                 HDF_LOGE("%{public}s: get axis info failed fd = %{public}d name = %{public}s errormsg = %{public}s",
265                          __func__, fd, detailInfo->attrSet.devName, strerror(errno));
266                 continue;
267             }
268         }
269     }
270     return INPUT_SUCCESS;
271 }
272 
GetInputDeviceTypeInfo(const string & devName)273 uint32_t GetInputDeviceTypeInfo(const string &devName)
274 {
275     uint32_t type {INDEV_TYPE_UNKNOWN};
276     if (devName.find("input_mt_wrapper") != std::string::npos) {
277         type = INDEV_TYPE_TOUCH;
278     } else if ((devName.find("Keyboard") != std::string::npos) &&
279                (devName.find("Headset") == std::string::npos)) {
280         type = INDEV_TYPE_KEYBOARD;
281     } else if (devName.find("Mouse") != std::string::npos) {
282         type = INDEV_TYPE_MOUSE;
283     } else if ((devName.find("_gpio_key") != std::string::npos) ||
284                (devName.find("ponkey_on") != std::string::npos) ||
285                (devName.find("powerkey") != std::string::npos) ||
286                (devName.find("gpiokeys") != std::string::npos)) {
287         type = INDEV_TYPE_KEY;
288     } else if (devName.find("Touchpad") != std::string::npos) {
289         type = INDEV_TYPE_TOUCHPAD;
290     }
291     return type;
292 }
293 
GetCurDevIndex()294 int32_t InputDeviceManager::GetCurDevIndex()
295 {
296     if (inputDevList_.size() >= DEV_INDEX_MAX) {
297         HDF_LOGE("%{public}s: The number of devices has reached max_num", __func__);
298         return INVALID_ID;
299     }
300     if (inputDevList_.count(devIndex_) == 0) {
301         return static_cast<int32_t>(devIndex_);
302     }
303     uint32_t newId = inputDevList_.size();
304     while (inputDevList_.count(newId) != 0) {
305         newId++;
306     }
307     return static_cast<int32_t>(newId);
308 }
309 
CreateInputDevListNode(InputDevListNode & inputDevNode,std::string & fileName)310 int32_t InputDeviceManager::CreateInputDevListNode(InputDevListNode &inputDevNode, std::string &fileName)
311 {
312     std::string devPathNode = devPath_ + "/" + fileName;
313     std::string::size_type n = devPathNode.find("event");
314     if (n == std::string::npos) {
315         HDF_LOGE("%{public}s: not found event node", __func__);
316         return CREATE_ERROR;
317     }
318     auto fd = OpenInputDevice(devPathNode);
319     if (fd < 0) {
320         HDF_LOGE("%{public}s: open node failed", __func__);
321         return CREATE_ERROR;
322     }
323     std::shared_ptr<InputDeviceInfo> detailInfo = std::make_shared<InputDeviceInfo>();
324     (void)memset_s(detailInfo.get(), sizeof(InputDeviceInfo), 0, sizeof(InputDeviceInfo));
325     (void)memset_s(&inputDevNode, sizeof(inputDevNode), 0, sizeof(inputDevNode));
326     (void)GetInputDeviceInfo(fd, detailInfo.get());
327     auto sDevName = string(detailInfo->attrSet.devName);
328     uint32_t type = GetInputDeviceTypeInfo(sDevName);
329     if (type == INDEV_TYPE_UNKNOWN) {
330         uint64_t ownerTag = fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DRIVERS_PERIPHERAL_INPUT_FDSAN_TAG);
331         fdsan_close_with_tag(fd, ownerTag);
332         HDF_LOGE("%{public}s: input device type unknow: %{public}d", __func__, type);
333         return CREATE_ERROR;
334     }
335     inputDevNode.index = devIndex_;
336     inputDevNode.status = INPUT_DEVICE_STATUS_OPENED;
337     inputDevNode.fd = fd;
338     detailInfo->devIndex = devIndex_;
339     detailInfo->devType = type;
340     if (memcpy_s(&inputDevNode.devPathNode, devPathNode.length(),
341         devPathNode.c_str(), devPathNode.length()) != EOK ||
342         memcpy_s(&inputDevNode.detailInfo, sizeof(InputDeviceInfo), detailInfo.get(),
343         sizeof(InputDeviceInfo)) != EOK) {
344         uint64_t ownerTag = fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DRIVERS_PERIPHERAL_INPUT_FDSAN_TAG);
345         fdsan_close_with_tag(fd, ownerTag);
346         HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
347         return MEMCPY_ERROR;
348     }
349     return CREATE_SUCCESS;
350 }
351 
LoadInputDevices(std::vector<std::string> & flist)352 void InputDeviceManager::LoadInputDevices(std::vector<std::string> &flist)
353 {
354     inputDevList_.clear();
355     InputDevListNode inputDevNode {};
356 
357     for (unsigned i = 0; i < flist.size(); i++) {
358         int32_t curDevIndex = GetCurDevIndex();
359         if (curDevIndex == INVALID_ID) {
360             return;
361         }
362         devIndex_ = static_cast<uint32_t>(curDevIndex);
363         int32_t ret = CreateInputDevListNode(inputDevNode, flist[i]);
364         if (ret == MEMCPY_ERROR) {
365             return;
366         }
367         if (ret == CREATE_SUCCESS) {
368             inputDevList_.insert_or_assign(devIndex_, inputDevNode);
369             devIndex_ += 1;
370         }
371     }
372 }
373 
ReloadInputDevices(std::vector<std::string> flist)374 void InputDeviceManager::ReloadInputDevices(std::vector<std::string> flist)
375 {
376     // 线程等待,保证input节点创建完成
377     std::this_thread::sleep_for(std::chrono::milliseconds(RELOAD_INTERVAL_MAX));
378     std::vector<std::string> curFileList = GetFiles(devPath_);
379     // 当前节点与首次加载数量不一致,需加载新的节点
380     if (curFileList.size() <= flist.size()) {
381         return;
382     }
383     InputDevListNode inputDevNode {};
384     for (unsigned i = 0; i < curFileList.size(); i++) {
385         if (std::find(flist.begin(), flist.end(), curFileList[i]) != flist.end()) {
386             continue;
387         }
388         int32_t curDevIndex = GetCurDevIndex();
389         if (curDevIndex == INVALID_ID) {
390             return;
391         }
392         devIndex_ = static_cast<uint32_t>(curDevIndex);
393         int32_t ret = CreateInputDevListNode(inputDevNode, flist[i]);
394         if (ret == MEMCPY_ERROR) {
395             return;
396         }
397         if (ret == CREATE_SUCCESS) {
398             inputDevList_.insert_or_assign(devIndex_, inputDevNode);
399             devIndex_ += 1;
400         }
401     }
402 }
403 
DoInputDeviceAction(void)404 int32_t InputDeviceManager::DoInputDeviceAction(void)
405 {
406     struct input_event evtBuffer[EVENT_BUFFER_SIZE] {};
407     int32_t result = 0;
408 
409     mEpollId_ = epoll_create1(EPOLL_CLOEXEC);
410     if (mEpollId_ == INPUT_FAILURE) {
411         HDF_LOGE("%{public}s: epoll create failed", __func__);
412         return mEpollId_;
413     }
414     mInotifyId_ = inotify_init();
415     result = inotify_add_watch(mInotifyId_, devPath_.c_str(), IN_DELETE | IN_CREATE);
416     if (result == INPUT_FAILURE) {
417         HDF_LOGE("%{public}s: add file watch failed", __func__);
418         return result;
419     }
420     AddToEpoll(mEpollId_, mInotifyId_);
421     bool hasDelOrCreate = false;
422     while (true) {
423         result = epoll_wait(mEpollId_, epollEventList_, EPOLL_MAX_EVENTS, EPOLL_WAIT_TIMEOUT);
424         if (result <= 0) {
425             continue;
426         }
427         hasDelOrCreate = false;
428         for (int32_t i = 0; i < result; i++) {
429             if (epollEventList_[i].data.fd != mInotifyId_) {
430                 DoRead(epollEventList_[i].data.fd, evtBuffer, EVENT_BUFFER_SIZE);
431                 continue;
432             }
433             hasDelOrCreate = true;
434         }
435         // The fd delete event occurred before the data was read
436         if (hasDelOrCreate && INPUT_FAILURE == InotifyEventHandler(mEpollId_, mInotifyId_)) {
437             HDF_LOGE("%{public}s: inotify handler failed", __func__);
438             return INPUT_FAILURE;
439         }
440     }
441     return INPUT_SUCCESS;
442 }
443 
DeleteDevListNode(int index)444 void InputDeviceManager::DeleteDevListNode(int index)
445 {
446     for (auto it = inputDevList_.begin(); it != inputDevList_.end();) {
447         if (it->first == (uint32_t)index) {
448             it = inputDevList_.erase(it);
449             if (devIndex_ < 1 || devIndex_ > DEV_INDEX_MAX) {
450                 return;
451             }
452             devIndex_ = it->first;
453         } else {
454             ++it;
455         }
456     }
457     return;
458 }
459 
AddDeviceNodeToList(int32_t & epollFd,int32_t & fd,string devPath,std::shared_ptr<InputDeviceInfo> & detailInfo)460 int32_t InputDeviceManager::AddDeviceNodeToList(
461     int32_t &epollFd, int32_t &fd, string devPath, std::shared_ptr<InputDeviceInfo> &detailInfo)
462 {
463     if (epollFd < 0 || fd < 0) {
464         HDF_LOGE("%{public}s: param invalid, %{public}d", __func__, __LINE__);
465         return INPUT_FAILURE;
466     }
467     int32_t curDevIndex = GetCurDevIndex();
468     if (curDevIndex == INVALID_ID) {
469         HDF_LOGE("%{public}s: input device exceeds the maximum limit, %{public}d", __func__, __LINE__);
470         return INPUT_FAILURE;
471     }
472     devIndex_ = static_cast<uint32_t>(curDevIndex);
473     InputDevListNode inputDevList {};
474     inputDevList.index = devIndex_;
475     inputDevList.status = INPUT_DEVICE_STATUS_OPENED;
476     inputDevList.fd = fd;
477     detailInfo->devIndex = devIndex_;
478     if (memcpy_s(inputDevList.devPathNode, devPath.length(), devPath.c_str(), devPath.length()) != EOK ||
479         memcpy_s(&inputDevList.detailInfo, sizeof(InputDeviceInfo), detailInfo.get(),
480         sizeof(InputDeviceInfo)) != EOK) {
481         HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
482         return INPUT_FAILURE;
483     }
484     inputDevList_.insert_or_assign(devIndex_, inputDevList);
485     if (AddToEpoll(epollFd, inputDevList.fd) != INPUT_SUCCESS) {
486         HDF_LOGE("%{public}s: add to epoll failed, line: %{public}d", __func__, __LINE__);
487         DeleteDevListNode(devIndex_);
488         return INPUT_FAILURE;
489     }
490     devIndex_ += 1;
491     return INPUT_SUCCESS;
492 }
493 
DoWithEventDeviceAdd(int32_t & epollFd,int32_t & fd,string devPath)494 void InputDeviceManager::DoWithEventDeviceAdd(int32_t &epollFd, int32_t &fd, string devPath)
495 {
496     bool findDeviceFlag = false;
497     uint32_t type {};
498     uint32_t index {};
499     uint32_t status {};
500 
501     std::shared_ptr<InputDeviceInfo> detailInfo = std::make_shared<InputDeviceInfo>();
502     (void)memset_s(detailInfo.get(), sizeof(InputDeviceInfo), 0, sizeof(InputDeviceInfo));
503     (void)GetInputDeviceInfo(fd, detailInfo.get());
504     auto sDevName = string(detailInfo->attrSet.devName);
505     for (auto it = inputDevList_.begin(); it != inputDevList_.end();) {
506         if (string(it->second.devPathNode) == devPath && string(it->second.detailInfo.attrSet.devName) == sDevName) {
507             it->second.fd = fd;
508             it->second.status = INPUT_DEVICE_STATUS_OPENED;
509             findDeviceFlag = true;
510             index = it->first;
511             break;
512         } else {
513             ++it;
514         }
515     }
516     if (sDevName.find("Keyboard") != std::string::npos) {
517         detailInfo->devType = INDEV_TYPE_KEYBOARD;
518     }
519     if (sDevName.find("Mouse") != std::string::npos) {
520         detailInfo->devType = INDEV_TYPE_MOUSE;
521     }
522     type = detailInfo->devType;
523     if (!findDeviceFlag) {
524         if (AddDeviceNodeToList(epollFd, fd, devPath, detailInfo) != INPUT_SUCCESS) {
525             HDF_LOGE("%{public}s: add device node failed, line: %{public}d", __func__, __LINE__);
526             return;
527         }
528     }
529     status = INPUT_DEVICE_STATUS_OPENED;
530     HDF_LOGI("%{public}s end", __func__);
531     SendHotPlugEvent(type, index, status);
532 }
533 
SendHotPlugEvent(uint32_t & type,uint32_t & index,uint32_t status)534 void InputDeviceManager::SendHotPlugEvent(uint32_t &type, uint32_t &index, uint32_t status)
535 {
536     HDF_LOGI("%{public}s start", __func__);
537     // hot plug evnets happened
538     InputHotPlugEvent *evtPlusPkg = (InputHotPlugEvent *)OsalMemAlloc(sizeof(InputHotPlugEvent));
539     if (evtPlusPkg == nullptr) {
540         HDF_LOGE("%{public}s: OsalMemAlloc failed", __func__);
541         return;
542     }
543 
544     evtPlusPkg->devType = type;
545     evtPlusPkg->devIndex = index;
546     evtPlusPkg->status = status;
547 
548     if (reportHotPlugEventCallback_ != nullptr) {
549         HDF_LOGD("devType: %{public}u devIndex: %{public}u status: %{public}u", type, index, status);
550         reportHotPlugEventCallback_->HotPlugCallback(evtPlusPkg);
551     }
552 
553     OsalMemFree(evtPlusPkg);
554     evtPlusPkg = nullptr;
555 }
556 
DoWithEventDeviceDel(int32_t & epollFd,uint32_t & index)557 void InputDeviceManager::DoWithEventDeviceDel(int32_t &epollFd, uint32_t &index)
558 {
559     uint32_t type {};
560     uint32_t devIndex {};
561     uint32_t status {};
562 
563     // hot plug evnets happened
564     auto sDevName = string(inputDevList_[index].detailInfo.attrSet.devName);
565     if (sDevName.find("Keyboard") != std::string::npos) {
566         type = INDEV_TYPE_KEYBOARD;
567     }
568     if (sDevName.find("Mouse") != std::string::npos) {
569         type = INDEV_TYPE_MOUSE;
570     }
571     auto ret = FindIndexFromDevName(sDevName, &devIndex);
572     if (ret != INPUT_SUCCESS) {
573         SendHotPlugEvent(type, devIndex_, status);
574         HDF_LOGE("%{public}s: no found device maybe it has been removed", __func__);
575         return;
576     }
577     status = INPUT_DEVICE_STATUS_CLOSED;
578     SendHotPlugEvent(type, devIndex, status);
579     CloseInputDevice(inputDevList_[index].devPathNode);
580     DeleteDevListNode(index);
581     HDF_LOGI("%{public}s: end", __func__);
582 }
583 
InotifyEventHandler(int32_t epollFd,int32_t notifyFd)584 int32_t InputDeviceManager::InotifyEventHandler(int32_t epollFd, int32_t notifyFd)
585 {
586     char InfoBuf[BUFFER_SIZE];
587     struct inotify_event *event {};
588     char nodeRealPath[PATH_MAX + 1] = { '\0' };
589     char *p {};
590     int32_t tmpFd {};
591 
592     (void)memset_s(InfoBuf, BUFFER_SIZE, 0, BUFFER_SIZE);
593     int32_t result = read(notifyFd, InfoBuf, BUFFER_SIZE);
594     for (p = InfoBuf; p < InfoBuf + result;) {
595         event = (struct inotify_event *)(p);
596         auto nodePath = devPath_ + "/" + string(event->name);
597         if (event->mask & IN_CREATE) {
598             if (realpath(nodePath.c_str(), nodeRealPath) == nullptr) {
599                 HDF_LOGE("%{public}s: The absolute path does not exist.", __func__);
600                 return INPUT_FAILURE;
601             }
602             tmpFd = open(nodeRealPath, O_RDWR);
603             if (tmpFd == INPUT_FAILURE) {
604                 HDF_LOGE("%{public}s: open file failure: %{public}s", __func__, nodeRealPath);
605                 return INPUT_FAILURE;
606             }
607             uint64_t ownerTag = fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DRIVERS_PERIPHERAL_INPUT_FDSAN_TAG);
608             fdsan_exchange_owner_tag(tmpFd, 0, ownerTag);
609             if (nodePath.find("event") == std::string::npos) {
610                 break;
611             }
612             DoWithEventDeviceAdd(epollFd, tmpFd, nodePath);
613         } else if (event->mask & IN_DELETE) {
614             for (auto &inputDev : inputDevList_) {
615                 if (!strcmp(inputDev.second.devPathNode, nodePath.c_str())) {
616                     DoWithEventDeviceDel(epollFd, inputDev.second.index);
617                     break;
618                 }
619             }
620         } else {
621             // do nothing
622             HDF_LOGI("%{public}s: others actions has done", __func__);
623         }
624         p += sizeof(struct inotify_event) + event->len;
625     }
626     return 0;
627 }
628 
AddToEpoll(int32_t epollFd,int32_t fileFd)629 int32_t InputDeviceManager::AddToEpoll(int32_t epollFd, int32_t fileFd)
630 {
631     int32_t result {0};
632     struct epoll_event eventItem {};
633 
634     (void)memset_s(&eventItem, sizeof(eventItem), 0, sizeof(eventItem));
635     eventItem.events = EPOLLIN;
636     eventItem.data.fd = fileFd;
637     result = epoll_ctl(epollFd, EPOLL_CTL_ADD, fileFd, &eventItem);
638     return result;
639 }
RemoveEpoll(int32_t epollFd,int32_t fileFd)640 void InputDeviceManager::RemoveEpoll(int32_t epollFd, int32_t fileFd)
641 {
642     epoll_ctl(epollFd, EPOLL_CTL_DEL, fileFd, nullptr);
643 }
644 
FindIndexFromFd(int32_t & fd,uint32_t * index)645 int32_t InputDeviceManager::FindIndexFromFd(int32_t &fd, uint32_t *index)
646 {
647     std::lock_guard<std::mutex> guard(lock_);
648     for (const auto &inputDev : inputDevList_) {
649         if (fd == inputDev.second.fd) {
650             *index = inputDev.first;
651             return INPUT_SUCCESS;
652         }
653     }
654     return INPUT_FAILURE;
655 }
656 
FindIndexFromDevName(string devName,uint32_t * index)657 int32_t InputDeviceManager::FindIndexFromDevName(string devName, uint32_t *index)
658 {
659     std::lock_guard<std::mutex> guard(lock_);
660     for (const auto &inputDev : inputDevList_) {
661         if (!strcmp(devName.c_str(), inputDev.second.detailInfo.attrSet.devName)) {
662             *index =  inputDev.first;
663             return INPUT_SUCCESS;
664         }
665     }
666     return INPUT_FAILURE;
667 }
668 
669 // InputManager
ScanDevice(InputDevDesc * staArr,uint32_t arrLen)670 RetStatus InputDeviceManager::ScanDevice(InputDevDesc *staArr, uint32_t arrLen)
671 {
672     if (staArr == nullptr) {
673         HDF_LOGE("%{public}s: param is null", __func__);
674         return INPUT_NULL_PTR;
675     }
676 
677     auto scanCount = (arrLen >= inputDevList_.size() ? inputDevList_.size() : arrLen);
678     if (inputDevList_.size() == 0) {
679         HDF_LOGE("%{public}s: inputDevList_.size is 0", __func__);
680         return INPUT_FAILURE;
681     }
682 
683     for (size_t i = 0; i <= scanCount; i++) {
684         (staArr + i)->devIndex = inputDevList_[i].index;
685         (staArr + i)->devType = inputDevList_[i].detailInfo.devType;
686     }
687 
688     return INPUT_SUCCESS;
689 }
690 
OpenDevice(uint32_t deviceIndex)691 RetStatus InputDeviceManager::OpenDevice(uint32_t deviceIndex)
692 {
693     std::lock_guard<std::mutex> guard(lock_);
694     auto ret = INPUT_FAILURE;
695 
696     if (deviceIndex >= inputDevList_.size()) {
697         HDF_LOGE("%{public}s: param is wrong", __func__);
698         return ret;
699     }
700     auto searchIndex = inputDevList_.find(deviceIndex);
701     if (searchIndex != inputDevList_.end()) {
702         if (searchIndex->second.status != INPUT_DEVICE_STATUS_OPENED) {
703             auto openRet = OpenInputDevice(searchIndex->second.devPathNode);
704             if (openRet > 0) {
705                 AddToEpoll(mEpollId_, openRet);
706                 ret = INPUT_SUCCESS;
707             } else {
708                 HDF_LOGE("%{public}s: open error: %{public}d errormsg: %{public}s",
709                          __func__, openRet, strerror(errno));
710                 return ret;
711             }
712             searchIndex->second.fd = openRet;
713         } else {
714             HDF_LOGD("%{public}s: open devPathNoth: %{public}s fd: %{public}d",
715                      __func__, searchIndex->second.devPathNode, searchIndex->second.fd);
716             HDF_LOGD("%{public}s: open devPathNoth: %{public}s status: %{public}d index: %{public}d",
717                      __func__, searchIndex->second.devPathNode, searchIndex->second.status, searchIndex->first);
718             AddToEpoll(mEpollId_, searchIndex->second.fd);
719             ret = INPUT_SUCCESS;
720         }
721     }
722     for (auto &e : inputDevList_) {
723         dumpInfoList(e.second);
724     }
725     return ret;
726 }
727 
CloseDevice(uint32_t deviceIndex)728 RetStatus InputDeviceManager::CloseDevice(uint32_t deviceIndex)
729 {
730     std::lock_guard<std::mutex> guard(lock_);
731     auto ret = INPUT_FAILURE;
732 
733     if (deviceIndex >= inputDevList_.size()) {
734         HDF_LOGE("%{public}s: param is wrong", __func__);
735         return ret;
736     }
737     auto searchIndex = inputDevList_.find(deviceIndex);
738     if (searchIndex != inputDevList_.end()) {
739         ret = CloseInputDevice(searchIndex->second.devPathNode);
740     }
741     HDF_LOGD("%{public}s: close devIndex: %{public}u ret: %{public}d inputDevList_ size:%{public}lu ",
742              __func__, deviceIndex, ret, inputDevList_.size());
743     return ret;
744 }
745 
GetDevice(int32_t deviceIndex,InputDeviceInfo ** devInfo)746 int32_t InputDeviceManager::GetDevice(int32_t deviceIndex, InputDeviceInfo **devInfo)
747 {
748     std::lock_guard<std::mutex> guard(lock_);
749     auto ret = INPUT_FAILURE;
750 
751     if (devInfo == nullptr || deviceIndex >= static_cast<int32_t>(inputDevList_.size()) || *devInfo != nullptr) {
752         HDF_LOGE("%{public}s: param is wrong", __func__);
753         return ret;
754     }
755     auto it = inputDevList_.find(deviceIndex);
756     if (it != inputDevList_.end()) {
757         int inputDeviceInfoSize = sizeof(InputDeviceInfo);
758         *devInfo = reinterpret_cast<InputDeviceInfo *>(OsalMemAlloc(inputDeviceInfoSize));
759         if (*devInfo == nullptr) {
760             HDF_LOGE("%{public}s: %{public}d OsalMemAlloc failed", __func__, __LINE__);
761             return ret;
762         }
763         if (memcpy_s(*devInfo, inputDeviceInfoSize, &it->second.detailInfo, inputDeviceInfoSize) != EOK) {
764             OsalMemFree(*devInfo);
765             HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
766             return ret;
767         }
768         ret = INPUT_SUCCESS;
769     }
770     HDF_LOGD("%{public}s: devIndex: %{public}d ret: %{public}d", __func__, deviceIndex, ret);
771     return ret;
772 }
773 
GetDeviceList(uint32_t * devNum,InputDeviceInfo ** deviceList,uint32_t size)774 int32_t InputDeviceManager::GetDeviceList(uint32_t *devNum, InputDeviceInfo **deviceList, uint32_t size)
775 {
776     std::lock_guard<std::mutex> guard(lock_);
777     auto ret = INPUT_FAILURE;
778 
779     auto scanCount = (size >= inputDevList_.size() ? inputDevList_.size() : size);
780     if ((devNum == nullptr) || (deviceList == nullptr) || inputDevList_.size() == 0 || *deviceList != nullptr) {
781         HDF_LOGE("%{public}s: param is wrong", __func__);
782         return ret;
783     }
784 
785     int inputDeviceInfoSize = sizeof(InputDeviceInfo);
786     *deviceList = reinterpret_cast<InputDeviceInfo *>(OsalMemAlloc(inputDeviceInfoSize * scanCount));
787     if (*deviceList == nullptr) {
788         HDF_LOGE("%{public}s: %{public}d OsalMemAlloc failed", __func__, __LINE__);
789         return ret;
790     }
791     for (size_t i = 0; i < scanCount; i++) {
792         if (memcpy_s((*deviceList) + i, inputDeviceInfoSize, &inputDevList_[i].detailInfo, inputDeviceInfoSize) !=
793             EOK) {
794             OsalMemFree(*deviceList);
795             HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
796             return ret;
797         }
798     }
799     *devNum = inputDevList_.size();
800     ret = INPUT_SUCCESS;
801     HDF_LOGD("%{public}s: devNum: %{public}u devIndex_: %{public}d", __func__, *devNum, devIndex_);
802 
803     return ret;
804 }
805 
806 // InputController
SetPowerStatus(uint32_t devIndex,uint32_t status)807 RetStatus InputDeviceManager::SetPowerStatus(uint32_t devIndex, uint32_t status)
808 {
809     RetStatus rc = INPUT_SUCCESS;
810     if ((devIndex >= inputDevList_.size()) || (status >= INPUT_POWER_STATUS_UNKNOWN)) {
811         HDF_LOGE("%{public}s: param is wrong", __func__);
812         return INPUT_FAILURE;
813     }
814     return rc;
815 }
816 
GetPowerStatus(uint32_t devIndex,uint32_t * status)817 RetStatus InputDeviceManager::GetPowerStatus(uint32_t devIndex, uint32_t *status)
818 {
819     RetStatus rc = INPUT_SUCCESS;
820     if ((devIndex >= inputDevList_.size()) || (status == nullptr)) {
821         HDF_LOGE("%{public}s: param is wrong", __func__);
822         return INPUT_FAILURE;
823     }
824     return rc;
825 }
826 
GetDeviceType(uint32_t devIndex,uint32_t * deviceType)827 RetStatus InputDeviceManager::GetDeviceType(uint32_t devIndex, uint32_t *deviceType)
828 {
829     RetStatus rc = INPUT_SUCCESS;
830     if ((devIndex >= inputDevList_.size()) || (deviceType == nullptr)) {
831         HDF_LOGE("%{public}s: param is wrong", __func__);
832         return INPUT_FAILURE;
833     }
834 
835     *deviceType = inputDevList_[devIndex].detailInfo.devType;
836     HDF_LOGI("%{public}s: devType: %{public}u", __func__, *deviceType);
837     return rc;
838 }
839 
GetChipInfo(uint32_t devIndex,char * chipInfo,uint32_t length)840 RetStatus InputDeviceManager::GetChipInfo(uint32_t devIndex, char *chipInfo, uint32_t length)
841 {
842     RetStatus rc = INPUT_SUCCESS;
843     if ((devIndex >= inputDevList_.size()) || (chipInfo == nullptr)) {
844         HDF_LOGE("%{public}s: param is wrong", __func__);
845         return INPUT_FAILURE;
846     }
847 
848     if (memcpy_s(chipInfo, length, inputDevList_[devIndex].detailInfo.chipInfo, length) != EOK) {
849         HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
850         rc = INPUT_FAILURE;
851     }
852     HDF_LOGI("%{public}s: chipInfo: %{public}s", __func__, chipInfo);
853     return rc;
854 }
855 
GetVendorName(uint32_t devIndex,char * vendorName,uint32_t length)856 RetStatus InputDeviceManager::GetVendorName(uint32_t devIndex, char *vendorName, uint32_t length)
857 {
858     RetStatus rc = INPUT_SUCCESS;
859     if ((devIndex >= inputDevList_.size()) || (vendorName == nullptr)) {
860         HDF_LOGE("%{public}s: param is wrong", __func__);
861         return INPUT_FAILURE;
862     }
863 
864     if (memcpy_s(vendorName, length, inputDevList_[devIndex].detailInfo.vendorName, length) != EOK) {
865         HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
866         rc = INPUT_FAILURE;
867     }
868     HDF_LOGI("%{public}s: vendorName: %{public}s", __func__, vendorName);
869     return rc;
870 }
871 
GetChipName(uint32_t devIndex,char * chipName,uint32_t length)872 RetStatus InputDeviceManager::GetChipName(uint32_t devIndex, char *chipName, uint32_t length)
873 {
874     RetStatus rc = INPUT_SUCCESS;
875     if ((devIndex >= inputDevList_.size()) || (chipName == nullptr)) {
876         HDF_LOGE("%{public}s: param is wrong", __func__);
877         return INPUT_FAILURE;
878     }
879 
880     if (memcpy_s(chipName, length, inputDevList_[devIndex].detailInfo.chipName, length) != EOK) {
881         HDF_LOGE("%{public}s: memcpy_s failed, line: %{public}d", __func__, __LINE__);
882         rc = INPUT_FAILURE;
883     }
884     HDF_LOGI("%{public}s: chipName: %{public}s", __func__, chipName);
885     return rc;
886 }
887 
SetGestureMode(uint32_t devIndex,uint32_t gestureMode)888 RetStatus InputDeviceManager::SetGestureMode(uint32_t devIndex, uint32_t gestureMode)
889 {
890     RetStatus rc = INPUT_SUCCESS;
891     if ((devIndex >= inputDevList_.size())) {
892         HDF_LOGE("%{public}s: param is wrong", __func__);
893         return INPUT_FAILURE;
894     }
895     return rc;
896 }
897 
RunCapacitanceTest(uint32_t devIndex,uint32_t testType,char * result,uint32_t length)898 RetStatus InputDeviceManager::RunCapacitanceTest(uint32_t devIndex, uint32_t testType, char *result, uint32_t length)
899 {
900     RetStatus rc = INPUT_SUCCESS;
901     if ((devIndex >= inputDevList_.size()) || (testType >= TEST_TYPE_UNKNOWN) ||
902         (result == nullptr) || (length < SELF_TEST_RESULT_LEN)) {
903         HDF_LOGE("%{public}s: param is wrong", __func__);
904         return INPUT_FAILURE;
905     }
906     return rc;
907 }
908 
RunExtraCommand(uint32_t devIndex,InputExtraCmd * cmd)909 RetStatus InputDeviceManager::RunExtraCommand(uint32_t devIndex, InputExtraCmd *cmd)
910 {
911     RetStatus rc = INPUT_SUCCESS;
912     if ((devIndex >= inputDevList_.size()) || (cmd == nullptr) || (cmd->cmdCode == nullptr ||
913         (cmd->cmdValue == nullptr))) {
914         HDF_LOGE("%{public}s: param is wrong", __func__);
915         return INPUT_FAILURE;
916     }
917     return rc;
918 }
919 
920 // InputReporter
RegisterReportCallback(uint32_t devIndex,InputEventCb * callback)921 RetStatus InputDeviceManager::RegisterReportCallback(uint32_t devIndex, InputEventCb *callback)
922 {
923     RetStatus rc = INPUT_SUCCESS;
924     if ((devIndex >= inputDevList_.size()) || (callback == nullptr) || (callback->EventPkgCallback == nullptr)) {
925         HDF_LOGE("%{public}s: param is wrong", __func__);
926         return INPUT_FAILURE;
927     }
928     std::lock_guard<std::mutex> guard(reportEventPkgCallBackLock_);
929     reportEventPkgCallback_[devIndex] = callback;
930     return rc;
931 }
932 
UnregisterReportCallback(uint32_t devIndex)933 RetStatus InputDeviceManager::UnregisterReportCallback(uint32_t devIndex)
934 {
935     HDF_LOGI("%{public}s: %{public}d dev is unregister", __func__, devIndex);
936     RetStatus rc = INPUT_SUCCESS;
937     if (devIndex >= inputDevList_.size()) {
938         HDF_LOGE("%{public}s: param is wrong", __func__);
939         return INPUT_FAILURE;
940     }
941     std::lock_guard<std::mutex> guard(reportEventPkgCallBackLock_);
942     reportEventPkgCallback_[devIndex] = nullptr;
943     return rc;
944 }
945 
RegisterHotPlugCallback(InputHostCb * callback)946 RetStatus InputDeviceManager::RegisterHotPlugCallback(InputHostCb *callback)
947 {
948     RetStatus rc = INPUT_SUCCESS;
949     reportHotPlugEventCallback_ = callback;
950     HDF_LOGI("%{public}s: called line %{public}d ret %{public}d", __func__, __LINE__, rc);
951     return rc;
952 }
953 
UnregisterHotPlugCallback(void)954 RetStatus InputDeviceManager::UnregisterHotPlugCallback(void)
955 {
956     RetStatus rc = INPUT_SUCCESS;
957     reportHotPlugEventCallback_ = nullptr;
958     HDF_LOGI("%{public}s: called line %{public}d ret:%{public}d", __func__, __LINE__, rc);
959     return rc;
960 }
961 
WorkerThread()962 void InputDeviceManager::WorkerThread()
963 {
964     HDF_LOGI("%{public}s: called line %{public}d ", __func__, __LINE__);
965     std::future<void> fuResult = std::async(std::launch::async, [this]() {
966         DoInputDeviceAction();
967         return;
968     });
969     fuResult.get();
970 }
971 }
972 }
973