1 /*
2 * Copyright (C) 2021 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 #include "host_usb.h"
16 #include <stdlib.h>
17 #include <thread>
18
19 #include "server.h"
20 namespace Hdc {
HdcHostUSB(const bool serverOrDaemonIn,void * ptrMainBase,void * ctxUSBin)21 HdcHostUSB::HdcHostUSB(const bool serverOrDaemonIn, void *ptrMainBase, void *ctxUSBin)
22 : HdcUSBBase(serverOrDaemonIn, ptrMainBase)
23 {
24 modRunning = false;
25 HdcServer *pServer = (HdcServer *)ptrMainBase;
26 ctxUSB = (libusb_context *)ctxUSBin;
27 uv_timer_init(&pServer->loopMain, &devListWatcher);
28 }
29
~HdcHostUSB()30 HdcHostUSB::~HdcHostUSB()
31 {
32 if (modRunning) {
33 Stop();
34 }
35 WRITE_LOG(LOG_DEBUG, "~HdcHostUSB");
36 }
37
Stop()38 void HdcHostUSB::Stop()
39 {
40 if (!ctxUSB) {
41 return;
42 }
43 Base::TryCloseHandle((uv_handle_t *)&devListWatcher);
44 modRunning = false;
45 }
46
Initial()47 int HdcHostUSB::Initial()
48 {
49 if (!ctxUSB) {
50 WRITE_LOG(LOG_FATAL, "USB mod ctxUSB is nullptr, recompile please");
51 return -1;
52 }
53 WRITE_LOG(LOG_DEBUG, "HdcHostUSB init");
54 modRunning = true;
55 StartupUSBWork(); // Main thread registration, IO in sub-thread
56 return 0;
57 }
58
UsbLogHandler(libusb_context * ctx,enum libusb_log_level level,const char * str)59 static void UsbLogHandler(libusb_context* ctx, enum libusb_log_level level, const char* str)
60 {
61 int l = -1;
62 switch (level) {
63 case LIBUSB_LOG_LEVEL_ERROR:
64 l = LOG_FATAL;
65 break;
66 case LIBUSB_LOG_LEVEL_WARNING:
67 l = LOG_WARN;
68 break;
69 case LIBUSB_LOG_LEVEL_INFO:
70 l = LOG_INFO;
71 break;
72 case LIBUSB_LOG_LEVEL_DEBUG:
73 l = LOG_DEBUG;
74 break;
75 default:
76 break;
77 }
78 if (l >= 0) {
79 char *newStr = strdup(str);
80 if (!newStr) {
81 return;
82 }
83 char *p = strstr(newStr, "libusb:");
84 if (!p) {
85 p = newStr;
86 }
87 char *q = strrchr(newStr, '\n');
88 if (q) {
89 *q = '\0';
90 }
91 WRITE_LOG(l, "%s", p);
92 free(newStr);
93 }
94 }
InitLogging(void * ctxUSB)95 void HdcHostUSB::InitLogging(void *ctxUSB)
96 {
97 if (ctxUSB == nullptr) {
98 WRITE_LOG(LOG_FATAL, "InitLogging failed ctxUSB is nullptr");
99 return;
100 }
101 std::string debugEnv = "LIBUSB_DEBUG";
102 libusb_log_level debugLevel;
103
104 switch (static_cast<Hdc::LogLevel>(Base::GetLogLevel())) {
105 case LOG_WARN:
106 debugLevel = LIBUSB_LOG_LEVEL_ERROR;
107 break;
108 case LOG_INFO:
109 debugLevel = LIBUSB_LOG_LEVEL_WARNING;
110 break;
111 case LOG_DEBUG:
112 debugLevel = LIBUSB_LOG_LEVEL_INFO;
113 break;
114 case LOG_VERBOSE:
115 debugLevel = LIBUSB_LOG_LEVEL_DEBUG;
116 break;
117 case LOG_FATAL:
118 // pass through to no libusb logging
119 default:
120 debugLevel = LIBUSB_LOG_LEVEL_NONE;
121 break;
122 }
123
124 libusb_set_option((libusb_context *)ctxUSB, LIBUSB_OPTION_LOG_LEVEL, debugLevel);
125 libusb_set_log_cb((libusb_context *)ctxUSB, UsbLogHandler,
126 LIBUSB_LOG_CB_CONTEXT | LIBUSB_LOG_CB_GLOBAL);
127
128 #ifdef _WIN32
129 debugEnv += "=";
130 debugEnv += std::to_string(debugLevel);
131 _putenv(debugEnv.c_str());
132 #else
133 setenv(debugEnv.c_str(), std::to_string(debugLevel).c_str(), 1);
134 #endif
135 }
136
DetectMyNeed(libusb_device * device,string & sn)137 bool HdcHostUSB::DetectMyNeed(libusb_device *device, string &sn)
138 {
139 HUSB hUSB = new(std::nothrow) HdcUSB();
140 if (hUSB == nullptr) {
141 WRITE_LOG(LOG_FATAL, "DetectMyNeed new hUSB failed");
142 return false;
143 }
144 hUSB->device = device;
145 // just get usb SN, close handle immediately
146 int childRet = OpenDeviceMyNeed(hUSB);
147 if (childRet < 0) {
148 WRITE_LOG(LOG_FATAL, "DetectMyNeed OpenDeviceMyNeed childRet:%d", childRet);
149 delete hUSB;
150 return false;
151 }
152 libusb_release_interface(hUSB->devHandle, hUSB->interfaceNumber);
153 libusb_close(hUSB->devHandle);
154 hUSB->devHandle = nullptr;
155
156 WRITE_LOG(LOG_INFO, "Needed device found, busid:%d devid:%d connectkey:%s", hUSB->busId, hUSB->devId,
157 hUSB->serialNumber.c_str());
158 // USB device is automatically connected after recognition, auto connect USB
159 UpdateUSBDaemonInfo(hUSB, nullptr, STATUS_READY);
160 HdcServer *hdcServer = (HdcServer *)clsMainBase;
161 HSession hSession = hdcServer->MallocSession(true, CONN_USB, this);
162 if (!hSession) {
163 WRITE_LOG(LOG_FATAL, "malloc usb session failed sn:%s", sn.c_str());
164 return false;
165 }
166 hSession->connectKey = hUSB->serialNumber;
167 uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
168 if (waitTimeDoCmd == nullptr) {
169 WRITE_LOG(LOG_FATAL, "DetectMyNeed new waitTimeDoCmd failed");
170 delete hUSB;
171 hdcServer->FreeSession(hSession->sessionId);
172 return false;
173 }
174 uv_timer_init(&hdcServer->loopMain, waitTimeDoCmd);
175 waitTimeDoCmd->data = hSession;
176 uv_timer_start(waitTimeDoCmd, hdcServer->UsbPreConnect, 0, DEVICE_CHECK_INTERVAL);
177 mapIgnoreDevice[sn] = HOST_USB_REGISTER;
178 delete hUSB;
179 return true;
180 }
181
KickoutZombie(HSession hSession)182 void HdcHostUSB::KickoutZombie(HSession hSession)
183 {
184 HdcServer *ptrConnect = (HdcServer *)hSession->classInstance;
185 HUSB hUSB = hSession->hUSB;
186 if (!hUSB->devHandle) {
187 WRITE_LOG(LOG_WARN, "KickoutZombie devHandle:%p isDead:%d", hUSB->devHandle, hSession->isDead);
188 return;
189 }
190 if (LIBUSB_ERROR_NO_DEVICE != libusb_kernel_driver_active(hUSB->devHandle, hUSB->interfaceNumber)) {
191 return;
192 }
193 WRITE_LOG(LOG_WARN, "KickoutZombie LIBUSB_ERROR_NO_DEVICE serialNumber:%s", hUSB->serialNumber.c_str());
194 ptrConnect->FreeSession(hSession->sessionId);
195 }
196
RemoveIgnoreDevice(string & mountInfo)197 void HdcHostUSB::RemoveIgnoreDevice(string &mountInfo)
198 {
199 if (mapIgnoreDevice.count(mountInfo)) {
200 mapIgnoreDevice.erase(mountInfo);
201 }
202 }
203
ReviewUsbNodeLater(string & nodeKey)204 void HdcHostUSB::ReviewUsbNodeLater(string &nodeKey)
205 {
206 HdcServer *hdcServer = (HdcServer *)clsMainBase;
207 // add to ignore list
208 mapIgnoreDevice[nodeKey] = HOST_USB_IGNORE;
209 int delayRemoveFromList = DEVICE_CHECK_INTERVAL * MINOR_TIMEOUT; // wait little time for daemon reinit
210 Base::DelayDo(&hdcServer->loopMain, delayRemoveFromList, 0, nodeKey, nullptr,
211 [this](const uint8_t flag, string &msg, const void *) -> void { RemoveIgnoreDevice(msg); });
212 }
213
WatchUsbNodeChange(uv_timer_t * handle)214 void HdcHostUSB::WatchUsbNodeChange(uv_timer_t *handle)
215 {
216 HdcHostUSB *thisClass = static_cast<HdcHostUSB *>(handle->data);
217 HdcServer *ptrConnect = static_cast<HdcServer *>(thisClass->clsMainBase);
218 libusb_device **devs = nullptr;
219 libusb_device *dev = nullptr;
220 // kick zombie
221 ptrConnect->EnumUSBDeviceRegister(KickoutZombie);
222 // find new
223 ssize_t cnt = libusb_get_device_list(thisClass->ctxUSB, &devs);
224 if (cnt < 0) {
225 WRITE_LOG(LOG_FATAL, "Failed to get device list");
226 return;
227 }
228 int i = 0;
229 // linux replug devid increment,windows will be not
230 while ((dev = devs[i++]) != nullptr) { // must postfix++
231 string szTmpKey = Base::StringFormat("%d-%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
232 // check is in ignore list
233 UsbCheckStatus statusCheck = thisClass->mapIgnoreDevice[szTmpKey];
234 if (statusCheck == HOST_USB_IGNORE || statusCheck == HOST_USB_REGISTER) {
235 continue;
236 }
237 string sn = szTmpKey;
238 if (thisClass->HasValidDevice(dev) && !thisClass->DetectMyNeed(dev, sn)) {
239 thisClass->ReviewUsbNodeLater(szTmpKey);
240 }
241 }
242 libusb_free_device_list(devs, 1);
243 }
244
HasValidDevice(libusb_device * device)245 bool HdcHostUSB::HasValidDevice(libusb_device *device)
246 {
247 struct libusb_config_descriptor *descConfig = nullptr;
248 int ret = libusb_get_active_config_descriptor(device, &descConfig);
249 if (ret != 0) {
250 WRITE_LOG(LOG_WARN, "get active config des fail, errno is %d.", errno);
251 return false;
252 }
253 bool hasValid = false;
254 for (unsigned int j = 0; j < descConfig->bNumInterfaces; ++j) {
255 const struct libusb_interface *interface = &descConfig->interface[j];
256 if (interface->num_altsetting < 1) {
257 continue;
258 }
259 const struct libusb_interface_descriptor *ifDescriptor = &interface->altsetting[0];
260 if (!IsDebuggableDev(ifDescriptor)) {
261 continue;
262 }
263 hasValid = true;
264 break;
265 }
266 return hasValid;
267 }
268
269 // Main thread USB operates in this thread
UsbWorkThread(void * arg)270 void HdcHostUSB::UsbWorkThread(void *arg)
271 {
272 HdcHostUSB *thisClass = (HdcHostUSB *)arg;
273 constexpr uint8_t usbHandleTimeout = 30; // second
274 while (thisClass->modRunning) {
275 struct timeval zerotime;
276 zerotime.tv_sec = usbHandleTimeout;
277 zerotime.tv_usec = 0; // if == 0,windows will be high CPU load
278 libusb_handle_events_timeout(thisClass->ctxUSB, &zerotime);
279 }
280 WRITE_LOG(LOG_DEBUG, "Host Sessionbase usb workthread finish");
281 }
282
StartupUSBWork()283 int HdcHostUSB::StartupUSBWork()
284 {
285 // Because libusb(winusb backend) does not support hotplug under win32, we use list mode for all platforms
286 WRITE_LOG(LOG_DEBUG, "USBHost loopfind mode");
287 devListWatcher.data = this;
288 uv_timer_start(&devListWatcher, WatchUsbNodeChange, 0, DEVICE_CHECK_INTERVAL);
289 // Running pendding in independent threads does not significantly improve the efficiency
290 uv_thread_create(&threadUsbWork, UsbWorkThread, this);
291 return 0;
292 }
293
CheckDescriptor(HUSB hUSB,libusb_device_descriptor & desc)294 int HdcHostUSB::CheckDescriptor(HUSB hUSB, libusb_device_descriptor& desc)
295 {
296 char serialNum[BUF_SIZE_MEDIUM] = "";
297 int childRet = 0;
298 uint8_t curBus = libusb_get_bus_number(hUSB->device);
299 uint8_t curDev = libusb_get_device_address(hUSB->device);
300 hUSB->busId = curBus;
301 hUSB->devId = curDev;
302 if (libusb_get_device_descriptor(hUSB->device, &desc)) {
303 WRITE_LOG(LOG_WARN, "CheckDescriptor libusb_get_device_descriptor failed %d-%d", curBus, curDev);
304 return -1;
305 }
306 // Get the serial number of the device, if there is no serial number, use the ID number to replace
307 // If the device is not in time, occasionally can't get it, this is determined by the external factor, cannot be
308 // changed. LIBUSB_SUCCESS
309 childRet = libusb_get_string_descriptor_ascii(hUSB->devHandle, desc.iSerialNumber, (uint8_t *)serialNum,
310 sizeof(serialNum));
311 if (childRet < 0) {
312 WRITE_LOG(LOG_WARN, "CheckDescriptor libusb_get_string_descriptor_ascii failed %d-%d", curBus, curDev);
313 return -1;
314 } else {
315 hUSB->serialNumber = serialNum;
316 }
317 WRITE_LOG(LOG_DEBUG, "CheckDescriptor busId-devId:%d-%d serialNum:%s", curBus, curDev, serialNum);
318 return 0;
319 }
320
321 // hSession can be null
UpdateUSBDaemonInfo(HUSB hUSB,HSession hSession,uint8_t connStatus)322 void HdcHostUSB::UpdateUSBDaemonInfo(HUSB hUSB, HSession hSession, uint8_t connStatus)
323 {
324 // add to list
325 HdcServer *pServer = (HdcServer *)clsMainBase;
326 HdcDaemonInformation di;
327 di.connectKey = hUSB->serialNumber;
328 di.connType = CONN_USB;
329 di.connStatus = connStatus;
330 di.hSession = hSession;
331 di.usbMountPoint = "";
332 di.usbMountPoint = Base::StringFormat("%d-%d", hUSB->busId, hUSB->devId);
333
334 HDaemonInfo pDi = nullptr;
335 HDaemonInfo hdiNew = &di;
336 pServer->AdminDaemonMap(OP_QUERY, hUSB->serialNumber, pDi);
337 if (!pDi) {
338 pServer->AdminDaemonMap(OP_ADD, hUSB->serialNumber, hdiNew);
339 } else {
340 pServer->AdminDaemonMap(OP_UPDATE, hUSB->serialNumber, hdiNew);
341 }
342 }
343
IsDebuggableDev(const struct libusb_interface_descriptor * ifDescriptor)344 bool HdcHostUSB::IsDebuggableDev(const struct libusb_interface_descriptor *ifDescriptor)
345 {
346 constexpr uint8_t harmonyEpNum = 2;
347 constexpr uint8_t harmonyClass = 0xff;
348 constexpr uint8_t harmonySubClass = 0x50;
349 constexpr uint8_t harmonyProtocol = 0x01;
350
351 if (ifDescriptor->bInterfaceClass != harmonyClass || ifDescriptor->bInterfaceSubClass != harmonySubClass ||
352 ifDescriptor->bInterfaceProtocol != harmonyProtocol) {
353 return false;
354 }
355 if (ifDescriptor->bNumEndpoints != harmonyEpNum) {
356 return false;
357 }
358 return true;
359 }
360
CheckActiveConfig(libusb_device * device,HUSB hUSB,libusb_device_descriptor & desc)361 int HdcHostUSB::CheckActiveConfig(libusb_device *device, HUSB hUSB, libusb_device_descriptor& desc)
362 {
363 struct libusb_config_descriptor *descConfig = nullptr;
364 int ret = libusb_get_active_config_descriptor(device, &descConfig);
365 if (ret != 0) {
366 #ifdef HOST_MAC
367 if ((desc.bDeviceClass == 0xFF)
368 && (desc.bDeviceSubClass == 0xFF)
369 && (desc.bDeviceProtocol == 0xFF)) {
370 ret = libusb_set_configuration(hUSB->devHandle, 1);
371 if (ret != 0) {
372 WRITE_LOG(LOG_WARN, "set config failed ret:%d", ret);
373 return -1;
374 }
375 }
376
377 ret = libusb_get_active_config_descriptor(device, &descConfig);
378 if (ret != 0) {
379 #endif
380 WRITE_LOG(LOG_WARN, "get active config descriptor failed ret:%d", ret);
381 return -1;
382 }
383 #ifdef HOST_MAC
384 }
385 #endif
386
387 ret = -1;
388 CheckUsbEndpoint(ret, hUSB, descConfig);
389 libusb_free_config_descriptor(descConfig);
390 return ret;
391 }
392
CheckUsbEndpoint(int & ret,HUSB hUSB,libusb_config_descriptor * descConfig)393 void HdcHostUSB::CheckUsbEndpoint(int& ret, HUSB hUSB, libusb_config_descriptor *descConfig)
394 {
395 unsigned int j = 0;
396 for (j = 0; j < descConfig->bNumInterfaces; ++j) {
397 const struct libusb_interface *interface = &descConfig->interface[j];
398 if (interface->num_altsetting < 1) {
399 WRITE_LOG(LOG_DEBUG, "interface->num_altsetting = 0, j = %d", j);
400 continue;
401 }
402 const struct libusb_interface_descriptor *ifDescriptor = &interface->altsetting[0];
403 if (!IsDebuggableDev(ifDescriptor)) {
404 WRITE_LOG(LOG_DEBUG, "IsDebuggableDev fail, j = %d", j);
405 continue;
406 }
407 WRITE_LOG(LOG_DEBUG, "CheckActiveConfig IsDebuggableDev passed and then check endpoint attr");
408 hUSB->interfaceNumber = ifDescriptor->bInterfaceNumber;
409 unsigned int k = 0;
410 for (k = 0; k < ifDescriptor->bNumEndpoints; ++k) {
411 const struct libusb_endpoint_descriptor *ep_desc = &ifDescriptor->endpoint[k];
412 if ((ep_desc->bmAttributes & 0x03) != LIBUSB_TRANSFER_TYPE_BULK) {
413 WRITE_LOG(LOG_DEBUG, "check ep_desc->bmAttributes fail, all %d k = %d, bmAttributes %d",
414 ifDescriptor->bNumEndpoints, k, ep_desc->bmAttributes);
415 continue;
416 }
417 if (ep_desc->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
418 hUSB->hostBulkIn.endpoint = ep_desc->bEndpointAddress;
419 hUSB->hostBulkIn.bulkInOut = true;
420 } else {
421 hUSB->hostBulkOut.endpoint = ep_desc->bEndpointAddress;
422 hUSB->wMaxPacketSizeSend = ep_desc->wMaxPacketSize;
423 hUSB->hostBulkOut.bulkInOut = false;
424 }
425 }
426 if (hUSB->hostBulkIn.endpoint == 0 || hUSB->hostBulkOut.endpoint == 0) {
427 WRITE_LOG(LOG_DEBUG, "hostBulkIn.endpoint %d hUSB->hostBulkOut.endpoint %d",
428 hUSB->hostBulkIn.endpoint, hUSB->hostBulkOut.endpoint);
429 break;
430 }
431 ret = 0;
432 }
433 }
434
435 // multi-thread calll
CancelUsbIo(HSession hSession)436 void HdcHostUSB::CancelUsbIo(HSession hSession)
437 {
438 WRITE_LOG(LOG_DEBUG, "HostUSB CancelUsbIo, ref:%u", uint32_t(hSession->ref));
439 HUSB hUSB = hSession->hUSB;
440 std::unique_lock<std::mutex> lock(hUSB->lockDeviceHandle);
441 if (!hUSB->hostBulkIn.isShutdown) {
442 if (!hUSB->hostBulkIn.isComplete) {
443 libusb_cancel_transfer(hUSB->hostBulkIn.transfer);
444 hUSB->hostBulkIn.cv.notify_one();
445 } else {
446 hUSB->hostBulkIn.isShutdown = true;
447 }
448 }
449 if (!hUSB->hostBulkOut.isShutdown) {
450 if (!hUSB->hostBulkOut.isComplete) {
451 libusb_cancel_transfer(hUSB->hostBulkOut.transfer);
452 hUSB->hostBulkOut.cv.notify_one();
453 } else {
454 hUSB->hostBulkOut.isShutdown = true;
455 }
456 }
457 }
458
459 // 3rd write child-hdc-workthread
460 // no use uvwrite, raw write to socketpair's fd
UsbToHdcProtocol(uv_stream_t * stream,uint8_t * appendData,int dataSize)461 int HdcHostUSB::UsbToHdcProtocol(uv_stream_t *stream, uint8_t *appendData, int dataSize)
462 {
463 HSession hSession = (HSession)stream->data;
464 unsigned int fd = hSession->dataFd[STREAM_MAIN];
465 fd_set fdSet;
466 struct timeval timeout = { 3, 0 };
467 FD_ZERO(&fdSet);
468 FD_SET(fd, &fdSet);
469 int index = 0;
470 int childRet = 0;
471
472 while (index < dataSize) {
473 childRet = select(fd + 1, nullptr, &fdSet, nullptr, &timeout);
474 if (childRet <= 0) {
475 constexpr int bufSize = 1024;
476 char buf[bufSize] = { 0 };
477 #ifdef _WIN32
478 strerror_s(buf, bufSize, errno);
479 #else
480 strerror_r(errno, buf, bufSize);
481 #endif
482 WRITE_LOG(LOG_FATAL, "select error:%d [%s][%d]", errno, buf, childRet);
483 break;
484 }
485 childRet = send(fd, reinterpret_cast<const char *>(appendData) + index, dataSize - index, 0);
486 if (childRet < 0) {
487 constexpr int bufSize = 1024;
488 char buf[bufSize] = { 0 };
489 #ifdef _WIN32
490 strerror_s(buf, bufSize, errno);
491 #else
492 strerror_r(errno, buf, bufSize);
493 #endif
494 WRITE_LOG(LOG_FATAL, "UsbToHdcProtocol senddata err:%d [%s]", errno, buf);
495 break;
496 }
497 index += childRet;
498 }
499 if (index != dataSize) {
500 WRITE_LOG(LOG_FATAL, "UsbToHdcProtocol partialsenddata err:%d [%d]", index, dataSize);
501 return ERR_IO_FAIL;
502 }
503 return index;
504 }
505
USBBulkCallback(struct libusb_transfer * transfer)506 void LIBUSB_CALL HdcHostUSB::USBBulkCallback(struct libusb_transfer *transfer)
507 {
508 auto *ep = reinterpret_cast<HostUSBEndpoint *>(transfer->user_data);
509 std::unique_lock<std::mutex> lock(ep->mutexIo);
510 bool retrySumit = false;
511 int childRet = 0;
512 do {
513 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
514 WRITE_LOG(LOG_FATAL, "USBBulkCallback1 failed, ret:%d", transfer->status);
515 break;
516 }
517 if (!ep->bulkInOut && transfer->actual_length != transfer->length) {
518 transfer->length -= transfer->actual_length;
519 transfer->buffer += transfer->actual_length;
520 retrySumit = true;
521 break;
522 }
523 } while (false);
524 while (retrySumit) {
525 childRet = libusb_submit_transfer(transfer);
526 if (childRet != 0) {
527 WRITE_LOG(LOG_FATAL, "USBBulkCallback2 failed, ret:%d", childRet);
528 transfer->status = LIBUSB_TRANSFER_ERROR;
529 break;
530 }
531 return;
532 }
533 ep->isComplete = true;
534 ep->cv.notify_one();
535 }
536
SubmitUsbBio(HSession hSession,bool sendOrRecv,uint8_t * buf,int bufSize)537 int HdcHostUSB::SubmitUsbBio(HSession hSession, bool sendOrRecv, uint8_t *buf, int bufSize)
538 {
539 HUSB hUSB = hSession->hUSB;
540 int timeout = 0;
541 int childRet = 0;
542 int ret = ERR_IO_FAIL;
543 HostUSBEndpoint *ep = nullptr;
544
545 if (sendOrRecv) {
546 timeout = GLOBAL_TIMEOUT * TIME_BASE;
547 ep = &hUSB->hostBulkOut;
548 } else {
549 timeout = 0; // infinity
550 ep = &hUSB->hostBulkIn;
551 }
552 hUSB->lockDeviceHandle.lock();
553 ep->isComplete = false;
554 do {
555 std::unique_lock<std::mutex> lock(ep->mutexIo);
556 libusb_fill_bulk_transfer(ep->transfer, hUSB->devHandle, ep->endpoint, buf, bufSize, USBBulkCallback, ep,
557 timeout);
558 childRet = libusb_submit_transfer(ep->transfer);
559 hUSB->lockDeviceHandle.unlock();
560 if (childRet < 0) {
561 WRITE_LOG(LOG_FATAL, "SubmitUsbBio libusb_submit_transfer failed, ret:%d", childRet);
562 break;
563 }
564 ep->cv.wait(lock, [ep]() { return ep->isComplete; });
565 if (ep->transfer->status != 0) {
566 WRITE_LOG(LOG_FATAL, "SubmitUsbBio transfer failed, status:%d", ep->transfer->status);
567 break;
568 }
569 ret = ep->transfer->actual_length;
570 } while (false);
571 return ret;
572 }
573
BeginUsbRead(HSession hSession)574 void HdcHostUSB::BeginUsbRead(HSession hSession)
575 {
576 HUSB hUSB = hSession->hUSB;
577 hUSB->hostBulkIn.isShutdown = false;
578 hUSB->hostBulkOut.isShutdown = false;
579 ++hSession->ref;
580 // loop read
581 std::thread([this, hSession, hUSB]() {
582 int childRet = 0;
583 int nextReadSize = 0;
584 int bulkInSize = hUSB->hostBulkIn.sizeEpBuf;
585 while (!hSession->isDead) {
586 // if readIO < wMaxPacketSizeSend, libusb report overflow
587 nextReadSize = (childRet < hUSB->wMaxPacketSizeSend ?
588 hUSB->wMaxPacketSizeSend : std::min(childRet, bulkInSize));
589 childRet = SubmitUsbBio(hSession, false, hUSB->hostBulkIn.buf, nextReadSize);
590 if (childRet < 0) {
591 WRITE_LOG(LOG_FATAL, "Read usb failed, ret:%d", childRet);
592 break;
593 }
594 childRet = SendToHdcStream(hSession, reinterpret_cast<uv_stream_t *>(&hSession->dataPipe[STREAM_MAIN]),
595 hUSB->hostBulkIn.buf, childRet);
596 if (childRet < 0) {
597 WRITE_LOG(LOG_FATAL, "SendToHdcStream failed, ret:%d", childRet);
598 break;
599 }
600 }
601 --hSession->ref;
602 auto server = reinterpret_cast<HdcServer *>(clsMainBase);
603 hUSB->hostBulkIn.isShutdown = true;
604 server->FreeSession(hSession->sessionId);
605 RemoveIgnoreDevice(hUSB->usbMountPoint);
606 WRITE_LOG(LOG_DEBUG, "Usb loop read finish");
607 }).detach();
608 }
609
610 // ==0 Represents new equipment and is what we need,<0 my need
OpenDeviceMyNeed(HUSB hUSB)611 int HdcHostUSB::OpenDeviceMyNeed(HUSB hUSB)
612 {
613 libusb_device *device = hUSB->device;
614 int ret = -1;
615 int OpenRet = libusb_open(device, &hUSB->devHandle);
616 if (OpenRet != LIBUSB_SUCCESS) {
617 WRITE_LOG(LOG_DEBUG, "libusb_open fail xret %d", OpenRet);
618 return ERR_LIBUSB_OPEN;
619 }
620 while (modRunning) {
621 libusb_device_handle *handle = hUSB->devHandle;
622 struct libusb_device_descriptor desc;
623 if (CheckDescriptor(hUSB, desc)) {
624 break;
625 }
626 if (CheckActiveConfig(device, hUSB, desc)) {
627 break;
628 }
629 // USB filter rules are set according to specific device pedding device
630 ret = libusb_claim_interface(handle, hUSB->interfaceNumber);
631 WRITE_LOG(LOG_DEBUG, "libusb_claim_interface ret %d, interfaceNumber %d",
632 ret, hUSB->interfaceNumber);
633 break;
634 }
635 if (ret) {
636 // not my need device, release the device
637 libusb_close(hUSB->devHandle);
638 hUSB->devHandle = nullptr;
639 }
640 return ret;
641 }
642
SendUSBRaw(HSession hSession,uint8_t * data,const int length)643 int HdcHostUSB::SendUSBRaw(HSession hSession, uint8_t *data, const int length)
644 {
645 int ret = ERR_GENERIC;
646 HdcSessionBase *server = reinterpret_cast<HdcSessionBase *>(hSession->classInstance);
647 ++hSession->ref;
648 ret = SubmitUsbBio(hSession, true, data, length);
649 if (ret < 0) {
650 WRITE_LOG(LOG_FATAL, "Send usb failed, ret:%d", ret);
651 CancelUsbIo(hSession);
652 hSession->hUSB->hostBulkOut.isShutdown = true;
653 server->FreeSession(hSession->sessionId);
654 }
655 --hSession->ref;
656 return ret;
657 }
658
FindDeviceByID(HUSB hUSB,const char * usbMountPoint,libusb_context * ctxUSB)659 bool HdcHostUSB::FindDeviceByID(HUSB hUSB, const char *usbMountPoint, libusb_context *ctxUSB)
660 {
661 libusb_device **listDevices = nullptr;
662 bool ret = false;
663 char tmpStr[BUF_SIZE_TINY] = "";
664 int busNum = 0;
665 int devNum = 0;
666 int curBus = 0;
667 int curDev = 0;
668
669 int device_num = libusb_get_device_list(ctxUSB, &listDevices);
670 WRITE_LOG(LOG_DEBUG, "device_num:%d", device_num);
671 if (device_num <= 0) {
672 libusb_free_device_list(listDevices, 1);
673 return false;
674 }
675 WRITE_LOG(LOG_DEBUG, "usbMountPoint:%s", usbMountPoint);
676 if (strchr(usbMountPoint, '-') && EOK == strcpy_s(tmpStr, sizeof(tmpStr), usbMountPoint)) {
677 *strchr(tmpStr, '-') = '\0';
678 busNum = atoi(tmpStr);
679 devNum = atoi(tmpStr + strlen(tmpStr) + 1);
680 } else {
681 return false;
682 }
683 WRITE_LOG(LOG_DEBUG, "busNum:%d devNum:%d", busNum, devNum);
684
685 int i = 0;
686 for (i = 0; i < device_num; ++i) {
687 struct libusb_device_descriptor desc;
688 if (LIBUSB_SUCCESS != libusb_get_device_descriptor(listDevices[i], &desc)) {
689 WRITE_LOG(LOG_DEBUG, "libusb_get_device_descriptor failed i:%d", i);
690 continue;
691 }
692 curBus = libusb_get_bus_number(listDevices[i]);
693 curDev = libusb_get_device_address(listDevices[i]);
694 WRITE_LOG(LOG_DEBUG, "curBus:%d curDev:%d", curBus, curDev);
695 if ((curBus == busNum && curDev == devNum)) {
696 hUSB->device = listDevices[i];
697 int childRet = OpenDeviceMyNeed(hUSB);
698 WRITE_LOG(LOG_DEBUG, "OpenDeviceMyNeed childRet:%d", childRet);
699 if (!childRet) {
700 ret = true;
701 } else {
702 string key = string(usbMountPoint);
703 RemoveIgnoreDevice(key);
704 }
705 break;
706 }
707 }
708 libusb_free_device_list(listDevices, 1);
709 return ret;
710 }
711
ReadyForWorkThread(HSession hSession)712 bool HdcHostUSB::ReadyForWorkThread(HSession hSession)
713 {
714 HdcUSBBase::ReadyForWorkThread(hSession);
715 return true;
716 };
717
718 // Determines that daemonInfo must have the device
ConnectDetectDaemon(const HSession hSession,const HDaemonInfo pdi)719 HSession HdcHostUSB::ConnectDetectDaemon(const HSession hSession, const HDaemonInfo pdi)
720 {
721 HdcServer *pServer = (HdcServer *)clsMainBase;
722 HUSB hUSB = hSession->hUSB;
723 hUSB->usbMountPoint = pdi->usbMountPoint;
724 hUSB->ctxUSB = ctxUSB;
725 if (!FindDeviceByID(hUSB, hUSB->usbMountPoint.c_str(), hUSB->ctxUSB)) {
726 pServer->FreeSession(hSession->sessionId);
727 RemoveIgnoreDevice(hUSB->usbMountPoint);
728 WRITE_LOG(LOG_DEBUG, "FindDeviceByID fail");
729 return nullptr;
730 }
731 UpdateUSBDaemonInfo(hUSB, hSession, STATUS_CONNECTED);
732 BeginUsbRead(hSession);
733 hUSB->usbMountPoint = pdi->usbMountPoint;
734 WRITE_LOG(LOG_DEBUG, "HSession HdcHostUSB::ConnectDaemon");
735
736 Base::StartWorkThread(&pServer->loopMain, pServer->SessionWorkThread, Base::FinishWorkThread, hSession);
737 // wait for thread up
738 while (hSession->childLoop.active_handles == 0) {
739 uv_sleep(1);
740 }
741 auto ctrl = pServer->BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
742 Base::SendToPollFd(hSession->ctrlFd[STREAM_MAIN], ctrl.data(), ctrl.size());
743 return hSession;
744 }
745 } // namespace Hdc
746